我正在制作一个旨在使用功能解决单词搜索的程序。我从功能find_horizontal获得的输出
是:['********RRIRAI', 'FUNCTIONRRIRAI', 'RAIOONFRCCPWON', 'PTCSNOBEUITOLO', 'BNCACIANTOSLIH', 'RBYOLILYNREFBT', 'HYYNOGESTIBRIY', 'AATTSIONCMCENP', 'UORTENRRCBFVAU', 'CEBEECVWIERORI', '*********TOPYF', 'PROCESSORTOPYF', 'OH********HSOS', 'OHCOMPUTERHSOS', 'YCYPRESREOSMRW', 'OATHBRMVTHHCTR', 'PGORWOOUIPSCHP']
问题在于,它已将行添加到Outpuz列表中一次,然后将找到的单词划掉,然后再将其划掉。我想要的输出是:['********RRIRAI', 'RAIOONFRCCPWON', 'PTCSNOBEUITOLO', 'BNCACIANTOSLIH', 'RBYOLILYNREFBT', 'HYYNOGESTIBRIY', 'AATTSIONCMCENP', 'UORTENRRCBFVAU', 'CEBEECVWIERORI', '*********TOPYF', 'OH********HSOS', 'YCYPRESREOSMRW', 'OATHBRMVTHHCTR', 'PGORWOOUIPSCHP']
这是我的完整代码:
if __name__ == '__main__':
Puzzle = ["FUNCTIONRRIRAI",
"RAIOONFRCCPWON",
"PTCSNOBEUITOLO",
"BNCACIANTOSLIH",
"RBYOLILYNREFBT",
"HYYNOGESTIBRIY",
"AATTSIONCMCENP",
"UORTENRRCBFVAU",
"CEBEECVWIERORI",
"PROCESSORTOPYF",
"OHCOMPUTERHSOS",
"YCYPRESREOSMRW",
"OATHBRMVTHHCTR",
"PGORWOOUIPSCHP"]
def load_words_to_find(file_name):
word_list = []
file = open(file_name, "r")
for line in file.readlines():
word_list.append(line)
word_list = list(map(lambda s: s.strip(), word_list))
return word_list
def find_horizontal(Puzzle, Words, ReplaceWith, Found):
# Parameters :- List:Puzzle, List:Words, Character:ReplaceWith, List:Found
# Return :- List:Outpuz, List:Found
# Find all words which are horizontally in place (left to right and right to left), return the puzzle and list of found words
add = True
Outpuz = []
for line in Puzzle:
for word in Words:
if word in line:
Found.append(word)
print("Found: ", word)
Outpuz.append(line.replace(word,ReplaceWith*len(word)))
add = False
if not add:
pass
elif add:
Outpuz.append(line)
Outpuz.append(line)
print(Outpuz)
return Outpuz, Found
find_horizontal(Puzzle, load_words_to_find("words.txt"), "*", [])
最佳答案
我一年前做了类似的事情。
https://github.com/BenMcLean981/Python-Wordsearch
我认为问题是Outpuz.append(line)只是添加了从拼图到输出的每一行。
您的文件名中有什么?发现了什么,Outpuz应该是什么?找到我猜是在拼图中找到的单词列表。但是,结果是什么呢?
ID从此更改:
if word in line:
Found.append(word)
print("Found: ", word)
Outpuz.append(line.replace(word,ReplaceWith*len(word)))
add = False
if not add:
pass
elif add:
Outpuz.append(line)
Outpuz.append(line
Outpuz.append(line)
对此:
if word in line:
Found.append(word)
print("Found: ", word)
Outpuz.append(line.replace(word,ReplaceWith*len(word)))
#Adds the line if it has the change
else:
Outpuz.append(line) #Adds the line if it doesnt have the change.