我的代码没有从单词列表中返回任何内容


a_file = open(r"C:UserslisinDesktopCodeBomb Partywordlist.txt", "r")
list_of_lists = []
for line in a_file:
stripped_line = line.strip()
line_list = stripped_line.split()
list_of_lists.append(line_list)
a_file.close()
wordlist = list_of_lists
contains = input("? ")
matches = [match for match in wordlist if str(contains) in match]
print(matches)

当我运行代码并放入任何字母时,它没有返回任何内容。wordlist有它,但它仍然没有返回任何东西。我正在尝试获取包含您输入内容的任何单词。

编辑:我不是很清楚我想要创造什么。想要能够输入一个字符串,比如"ee",并让它返回任何具有"ee"在它们里面,像"蜜蜂"。或";free"

固定!原来它是在列一个清单的清单,而我不知何故没有意识到这一点。所以我把list转换成字符串然后把它分隔成list

def Convert(string):
li = list(string.split(" "))
return li
with a_file as myfile:
x = myfile.read().replace('n', ' ')
如果我没有说清楚我想要什么,我很抱歉。谢谢

您的问题是如何填充matchesmatch是一个字符串列表,而不是字符串本身,这就是为什么条件永远不会满足的原因。

我假设你想要containswordlist中的每一次出现。为了解决这个问题,您需要一个坐标列表为(line, word)。如果我像你一样写tuple/int:

matches = [(index_line, index_word) for index_line, line_list in enumerate(wordlist) for index_word, word in enumerate(line_list) if word == contains]

我认为这很难读。我建议这样做:

matches = []
for index_line, line_list in enumerate(wordlist):
for index_word, word in enumerate(line_list):
if word == contains:
matches.append((index_line, index_word))
print("Occurence(s) of the word can be found at :")
for match in matches:
print(f"  Line {match[0]}, word {match[1]}")

你也可以使用函数:

def matches(wordlist : list, contains : str) -> list:
for index_line, line_list in enumerate(wordlist):
for index_word, word in enumerate(line_list):
if word == contains:
yield (index_line, index_word)
print("Occurence(s) of the word can be found at :")
for match in matches(wordlist, contains):
print(f"  Line {match[0]}, word {match[1]}")

enumerate()返回两个变量:列表中元素的索引和元素本身。yield更难理解,它让你读取这个问题的答案。

输入:

你好!

我的名字是约翰

你呢?

John too !

contains = "John"

输出:

该词的出现位置为:

第二行,第4字

第4行,第1字

最新更新