【问题标题】:How to search a text file for a specific word in Python如何在 Python 中搜索文本文件中的特定单词
【发布时间】:2015-01-31 21:08:16
【问题描述】:

我想在文本文件中查找与存储在名为 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())

【问题讨论】:

    标签: python list class


    【解决方案1】:

    这可能会更干净一些。我觉得在这里上课有点矫枉过正。

    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"
    

    【讨论】:

      【解决方案2】:

      在匹配https://docs.python.org/3/howto/regex.html时没有什么比正则表达式更好的了

      items=['one','two','three','four','five'] #your items list created previously
      import re
      file=open('text.txt','r') #load your file
      content=file.read() #save the read output so the reading always starts from begining
      for i in items:
          lis=re.findall(i,content)
          if len(lis)==0:
              print('Not found')
          elif len(lis)==1:
              print('Found Once')
          elif len(lis)==2:
              print('Found Twice')
          else:
              print('Found',len(lis),'times')
      

      【讨论】:

      • 那解决不了任何问题。请提交完整的答案,而不仅仅是链接和伪造的代码被剪断
      • 我试图给提问者一个提示让他自己尝试,现在这里有一个更详细的答案
      【解决方案3】:

      您可以通过以下方式使用正则表达式:

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

      第二个命令创建一个由“|”分隔的可接受单词列表。要在文件上运行它,只需将 'the red car drive by the woman' 中的字符串替换为 open(your_file,'r').read()

      【讨论】:

        猜你喜欢
        • 2017-08-28
        • 1970-01-01
        • 2022-12-06
        • 1970-01-01
        • 1970-01-01
        • 2014-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多