在任意位置拆分列表项

2024-09-27 14:15:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

例如,返回:

['ward', 'robe']

['dent', 'ist']

...

但我想要的结果是:

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

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

...

关于如何得到这个结果有什么想法吗?你知道吗


Tags: or文件方法代码intxt列表for
3条回答

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

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']
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

关于:

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')

相关问题 更多 >

    热门问题