如何在Python中的文本文件中搜索特定单词 [英] How to search a text file for a specific word in Python

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

问题描述

我想在文本文件中找到与存储在称为项的现有列表中的单词匹配的单词,该列表是在上一个函数中创建的,并且我也希望能够在下一个函数中使用该列表,但是我不知道如何做到这一点,我尝试为此使用类,但我做对了.我无法弄清楚其余的代码是什么问题.我尝试在没有类和列表的情况下运行它,并用打开的文本文件中的一个单词替换了第8行中的列表"items []",尽管没有出现错误,它仍然没有执行任何操作.运行以下代码时,它会打印出:请输入有效的文本文件名称:",并在此处停止.

I want to find words in a text file that match words stored in an existing list called items, the list is created in a previous function and I want to be able to use the list in the next function as well but I'm unsure how to do that, I tried using classes for that but i couldn't get it right. And I can't figure out what the problem is with the rest of the code. I tried running it without the class and list and replaced the list 'items[]' in line 8 with a word in the text file being opened and it still didn't do anything, even though no errors come up. When the below code is run it prints out: "Please entre a valid textfile name: " and it stops there.

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") 

该列表是从另一个文本文件创建的,该文件包含前一个函数中的单词,该函数看起来像这样,并且可以在需要帮助的情况下正常工作.

The list is created from another text file containing words in a previous function that looks like this and it works as it should, if it is to any help:

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

print(createlist())

推荐答案

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

You can use regexp the following way:

    >>> 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']

第二个命令创建一个用"|"分隔的可接受单词的列表.要在文件上运行此文件,只需将女人开车的红色汽车"中的字符串替换为 open(your_file,'r').read().

The second command creates a list of acceptable words separated by "|". To run this on a file, just replace the string in 'the red car driven by the woman' for open(your_file,'r').read().

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

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