Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用python匹配文本文件中的单词?_Python_String_Match_Text Files - Fatal编程技术网

如何使用python匹配文本文件中的单词?

如何使用python匹配文本文件中的单词?,python,string,match,text-files,Python,String,Match,Text Files,我想搜索并匹配文本文件中的特定单词 with open('wordlist.txt', 'r') as searchfile: for line in searchfile: if word in line: print line 此代码甚至返回包含目标单词子字符串的单词。例如,如果单词是“there”,则搜索返回“there”、“Thouse”、“Three”等 我希望代码只返回包含“there”的行。句号。将行

我想搜索并匹配文本文件中的特定单词

with open('wordlist.txt', 'r') as searchfile:
        for line in searchfile:
            if word in line:
                    print line
此代码甚至返回包含目标单词子字符串的单词。例如,如果单词是“there”,则搜索返回“there”、“Thouse”、“Three”等


我希望代码只返回包含“there”的行。句号。

将行拆分为标记:
如果行中有单词。拆分():


re.search
函数扫描字符串
,如果找到第一个参数中定义的正则表达式,则返回true,忽略
re.I
的大小写。
^
字符表示“行首”,而
$
字符表示“行尾”。因此,搜索函数只有在匹配时才会返回true,前面是行的开头,后面是行的结尾,也就是独立的。

您应该使用正则表达式。Python文档中的代码可能是一个很好的起点。

查找re模块(正则表达式)。使用正则表达式“there”进行重新搜索是您想要的。

您始终可以使用正则表达式,大致如下:

import re

with open('wordlist.txt', 'r') as searchfile:
        for line in searchfile:
            if re.search( r'\sthere\s', line, re.M|re.I):
                    print line
  • \s它们\s
    -任何空格后跟“there”再后跟任何空格
  • re.I
    -表示不区分大小写
  • re.M
    -在这种情况下并不重要(因为行只有1\n)

与regex相比,它可能是性能更高的解决方案,但在某些情况下可能会出现问题(我不能肯定,因为我不知道输入是什么样子)+为了简单起见,不客气。但正如其他人所说,学习正则表达式。这需要一段时间,但值得。pydoc reSome对代码的解释会很好,因为OP显然不熟悉正则表达式的概念。这不会有同样的问题吗?也许“^*there*$”会更好?如果没有任何输入的指示,很难匹配所有的角情况<代码>\b此处\b可能比
^there$
更好。输入文件包含两列:例如-50677 Dedereds,类似r'\b此处\b'的内容更好<代码>\b匹配单词边界,而不使用像
\s
那样的字符。
import re

with open('wordlist.txt', 'r') as searchfile:
        for line in searchfile:
            if re.search( r'\sthere\s', line, re.M|re.I):
                    print line