如何使用Python在文本文件中查找单词

如何使用Python在文本文件中查找单词,python,text,Python,Text,我是python新手,正在尝试用python创建一个函数,用于在文本文件中查找单词出现的行并打印行号。该函数将文本文件名和单词列表作为输入。我不知道从哪里开始 范例 index("notes.txt",["isotope","proton","electron","neutron"]) 同位素1 质子3 电子2 中子5 这是我用文本编写的一些随机代码;所以,我不知道它是否能帮助我 def index(): infile=open("test.txt", "r") content

我是python新手,正在尝试用python创建一个函数,用于在文本文件中查找单词出现的行并打印行号。该函数将文本文件名和单词列表作为输入。我不知道从哪里开始

范例

index("notes.txt",["isotope","proton","electron","neutron"])
同位素1 质子3 电子2 中子5

这是我用文本编写的一些随机代码;所以,我不知道它是否能帮助我

def index():
    infile=open("test.txt", "r")
    content=infile.read()
    print(content)
    infile.close()
目标是能够在文本文件中找到单词,就像人们在书籍索引中找到单词一样

words = ['isotope', 'proton', 'electron', 'neutron']

def line_numbers(file_path, word_list):

    with open(file_path, 'r') as f:
        results = {word:[] for word in word_list}
        for num, line in enumerate(f, start=1):
            for word in word_list:
                if word in line:
                    results[word].append(num)
    return results
这将返回一个字典,其中包含给定单词的所有匹配项,区分大小写

演示

试着这样做:

def word_find(line,words):
    return list(set(line.strip().split()) & set(words))

def main(file,words):
    with open('file') as f:
        for i,x in enumerate(f, start=1):
            common = word_find(x,words)
            if common:
                print i, "".join(common)

if __name__ == '__main__':
    main('file', words)
破蟒蛇3.7。我需要映射到一个字符串,如下所示:

for word, lines in result.items():
    print(word, ": ", ', '.join(map(str,lines)))

grep怎么了?如果这是一个dup,或者其他什么问题,如果一个单词出现在多行上怎么办?我希望能够发布该单词出现的所有行。看起来人们只是在对所有答案进行向下投票,因为这是一个公认的格式错误的问题。我本来想找一个确切的哑巴,但我找不到任何与一系列单词相匹配的东西。很抱歉,我的问题没有用更好的措辞。我在社区学院上python课,这是我的家庭作业。我已经做了几天了,但是我想不出来。赋值表示该函数以文本文件名和单词列表作为输入。我没有投任何人的反对票。无论如何,谢谢大家的回答!
for word, lines in result.items():
    print(word, ": ", ', '.join(map(str,lines)))