在随机位置

时间:2017-01-31 20:52:01

标签: python split

我的.txt文件包含单词(所有两个或三个音节单词,.txt文件中新行上的每个单词),使用' - '连字符。我正在寻找一种方法来将这个' - '的位置随机地移到试验的一个地方向左或向右。这是将每个单词作为音节列表返回的代码:

for thisTrial in trials:
    wordList = thisTrial['word'].split("-")
    print wordList

这将返回例如:

  

['ward','robe']

     

['dent','ist']

     

...

但我想要的结果是:

  

['war','drobe']或['wardr','obe']

     

['den','tist']或['denti','st']

     

...

有关如何获得此结果的任何想法?

3 个答案:

答案 0 :(得分:0)

如果每个单词中只有一个连字符

from random import random

for word in ["hel-lo", "worl-d"]:
  pos = word.find("-")
  mov = 1 if random() > 0.5 else -1
  new_word = word.replace("-", "")
  split = [new_word[0:pos+mov], new_word[pos+mov:]]
  print(split)

#=> ['he', 'llo']
#=> ['world', '']
# or
#=> ['hell', 'o']
#=> ['wor', 'ld']

答案 1 :(得分:0)

from random import randint   
results = [] 
for i in range(1,15):
   randomSlicePt = random.randint(1,len(word))
   results.append(word[0:randomSlicePt] + '-' + word[randomSlicePt:len(word)])


>>> results
['ward-robe', 'wardro-be', 'wardr-obe', 'war-drobe', 'ward-robe', 'war-drobe', 'wardr-obe', 'wa-rdrobe', 'wa-rdrobe', 'wardr-obe', 'ward-robe', 'wardrobe-', 'war-drobe', 'war-drobe']

或者你不再关心连字符,而只是想通过一些随机的单词拨打。

results = [] 
def trial(word):
     randomSlicePt = random.randint(1,len(word))
     answer = []
     answer.append(word[0:randomSlicePt])
     answer.append(word[randomSlicePt:len(word)])
     results.append(answer)

for word in wordlist:
       trial(word) 
results

答案 2 :(得分:0)

怎么样:

import random
def test():
    word      = "ward-robe"
    delimiter = word.find('-')
    word      = word.replace('-','')
    l = [1,-1][random.getrandbits(1)]
    result = word[0:d-l],word[d-l:]
    print(result)

> test()
('war', 'drobe')

> test()
('wardr', 'obe')