Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.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_Wildcard - Fatal编程技术网

如何在Python中使用通配符创建搜索词?

如何在Python中使用通配符创建搜索词?,python,wildcard,Python,Wildcard,我想检查文档中是否包含某个术语。然而,有时这个词有几种形式(复数、过去时等) 如何创建搜索词来查找所有实例,例如 '*ello* World*' 其中star是一个通配符,不一定要包含在单词中 我找到了fnmatch模块的文档,但我看不出它如何帮助我搜索文档。你能使用正则表达式吗 import re m = re.search('\.*ello', somefile) 详情如下: 使用正则表达式,只需在文件中循环: import re f=open('test.file.here', 'r'

我想检查文档中是否包含某个术语。然而,有时这个词有几种形式(复数、过去时等)

如何创建搜索词来查找所有实例,例如

'*ello* World*'
其中star是一个通配符,不一定要包含在单词中


我找到了fnmatch模块的文档,但我看不出它如何帮助我搜索文档。

你能使用正则表达式吗

import re
m = re.search('\.*ello', somefile)
详情如下:


使用正则表达式,只需在文件中循环:

import re
f=open('test.file.here', 'r')

pattern = re.compile("^[^\s]*ello[^\s]*\sWorld[^\s]*$")

for line in f:
  if pattern.match(line):
    print line,

f.close()

您描述的*语法称为。它不适用于文档,只适用于文件和目录。正如其他人所指出的,正则表达式就是答案。

如果你在做任何复杂的事情,正则表达式就是最好的选择。如果你对这些不满意,我想对于你的具体问题,你也可以用“in”。例如:

x = 'hello world'
if 'ello' in x and 'world' in x':
     print 'matches'
else:
     print 'does not match'

我通常会选择正则表达式,但如果出于某种原因,您希望使用通配符格式,则可以这样做:

from fnmatch import fnmatch

pattern = '*ello* World*'

with open('sample.txt') as file:
    for line in f:
        if fnmatch(line, pattern):
            print(line)

听起来你可能想要词干或一些NLTK的东西…除了存在
fnmatch
。根据,fnmatch是用于文件名的。它使用“filename”作为参数非常多,但没有任何地方说它只用于文件名。在玩了一会儿之后,如果你用一个“非常感谢”的“光离子化”开始和结束你的图案,它似乎会起作用。这正是我想要的。“正则表达式通常更好。”是的,嗯。。。这正是你的观点,伙计。哈哈,我想说的是,当你在寻找一些通配符无法工作的非常精确的东西时,它们会更好。对于其他方面,通配符可能更好。更易于学习、编写和维护。但是,嘿。。。这正是我的看法,伙计…:)你说得对!我编辑了这篇文章以缓和我的意见。
from fnmatch import fnmatch

pattern = '*ello* World*'

with open('sample.txt') as file:
    for line in f:
        if fnmatch(line, pattern):
            print(line)