我有一个字符序列“ -------”,我想用正确范围内的“ jaillir”中的每个字母替换其中的每个“-”。
我该怎么做? 这是我的代码
import random
with open ("lexique.txt", "r", encoding= "utf8") as a:
words = []
letters = []
tirets= []
for line in a:
ligne = line[:-1]
words.append(ligne)
choix = random.choice(words)
tiret = ('-'* len(choix))
print(tiret)
print(choix)
accompli = False
while not accompli:
lettre = input("Entrez une lettre du mot ")
for t in range(len(tiret)):
if lettre in choix:
tiret.replace(tiret[t], lettre[t])
print(tiret)
答案 0 :(得分:0)
我认为您需要修复文件读取代码,即使这不是问题,如下所示:
with open('lexique.txt', r) as f:
text = f.read() # get file contents
接下来用一个单词替换----,我假设您文本中的破折号将永远与该单词相同,因此:
word = 'word' # any string e.g. word
dashes = '-' * len(word)
所以现在您可以像这样使用python的string.replace方法:
text = text.replace(dashes, word) # every time it finds the sequence of dashes it will be replaced by your word
带有for循环(逐步替换):
word = 'word' # any word
length = len(word)
temp = ''
for i, letter in enumerate(text):
if letter == '-':
if i + len(tempword) < len(text):
characters = [True if l == '-' else False for l in text[i:i + len(tempword)]]
if not(False in characters):
new += tempword[0]
if len(tempword) > 1:
tempword = tempword[1:]
else:
tempword = word
else:
new += letter
else:
new += letter
print(new)