如何使用 Python 在文本文件中查找单词 [英] How to find words in text files with Python

查看:82
本文介绍了如何使用 Python 在文本文件中查找单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to python and am trying to create a function in python that finds the lines where the word occurs in a text file and prints the line numbers. The function takes the text file name and list of words as input. I don't know where to start.

示例

index("notes.txt",["isotope","proton","electron","neutron"])

同位素1
质子3
电子2
中子 5

isotope 1
proton 3
electron 2
neutron 5

这是我用文本制作的一些随机代码;所以,不知道能不能帮到我.

This is some random code that I made with text; so, I don't know if it can help me or not.

def index():
    infile=open("test.txt", "r")
    content=infile.read()
    print(content)
    infile.close()

目标是能够在文本文件中找到单词,就像人们在书籍索引中查找单词一样.

The goal is to be able to find the words in the text file like a person would find a word in the index of a book.

推荐答案

试试这个:

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)

这篇关于如何使用 Python 在文本文件中查找单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆