如何在Python中搜索特定单词的文本文件

如何在Python中搜索特定单词的文本文件,python,list,class,Python,List,Class,我想在文本文件中查找与现有列表(名为items)中存储的单词相匹配的单词,该列表是在以前的函数中创建的,我想在下一个函数中也能使用该列表,但我不确定如何做到这一点,我尝试使用类来实现它,但我无法正确实现。我不知道剩下的代码有什么问题。我尝试在没有类和列表的情况下运行它,并将第8行中的列表“items[]”替换为正在打开的文本文件中的一个单词,但它仍然没有做任何事情,即使没有出现错误。当运行下面的代码时,它会打印出来:请输入一个有效的文本文件名:并在那里停止 class searchtext():

我想在文本文件中查找与现有列表(名为items)中存储的单词相匹配的单词,该列表是在以前的函数中创建的,我想在下一个函数中也能使用该列表,但我不确定如何做到这一点,我尝试使用类来实现它,但我无法正确实现。我不知道剩下的代码有什么问题。我尝试在没有类和列表的情况下运行它,并将第8行中的列表“items[]”替换为正在打开的文本文件中的一个单词,但它仍然没有做任何事情,即使没有出现错误。当运行下面的代码时,它会打印出来:请输入一个有效的文本文件名:并在那里停止

class searchtext():
    textfile = input("Please entre a valid textfile name: ")
    items = []

    def __init__search(self):
        with open("textfile") as openfile:
            for line in openfile:
                for part in line.split():
                    if ("items[]=") in part:
                        print (part)
                    else:
                        print("not found") 
该列表是从另一个文本文件中创建的,该文件包含前面函数中的单词,该函数如下所示,如果有任何帮助,它将按其应有的方式工作:

def createlist():
    items = []
    with open('words.txt') as input:
        for line in input:
            items.extend(line.strip().split(','))
    return items

print(createlist())

这可能更干净一点。我觉得在这里上课太过分了

def createlist():
    items = []
    with open('words.txt') as input:
        for line in input:
            items.extend(line.strip().split(','))
    return items

print(createlist())
# store the list
word_list = createlist()

with open('file.txt') as f:
    # split the file content to words (first to lines, then each line to it's words)
    for word in (sum([x.split() for x in f.read().split('\n')], [])):
        # check if each word is in the list
        if word in word_list:
            # do something with word
            print word + " is in the list"
        else:
            # word not in list
            print word + " is NOT in the list"

在匹配中没有什么比正则表达式更好的了


可以通过以下方式使用regexp:

    >>> import re
    >>> words=['car','red','woman','day','boston']
    >>> word_exp='|'.join(words)
    >>> re.findall(word_exp,'the red car driven by the woman',re.M)
    ['red', 'car', 'woman']

第二个命令创建一个由|分隔的可接受单词列表。要在文件上运行此操作,只需替换打开您的_文件“r”的“女人驾驶的红色汽车”中的字符串。

这并不能解决任何问题。请提交一个完整的答案,而不仅仅是链接和假代码snippedI试图给提问者一个提示,让他自己尝试,现在这里有一个更好的详细答案
    >>> import re
    >>> words=['car','red','woman','day','boston']
    >>> word_exp='|'.join(words)
    >>> re.findall(word_exp,'the red car driven by the woman',re.M)
    ['red', 'car', 'woman']