簡體   English   中英

如何在 Python 中使用通配符創建搜索詞?

[英]How can I create search terms with wildcards in Python?

我想檢查文檔中是否包含某個術語。 然而,有時,這個詞在幾個 forms (復數,過去時等)。

'Hello Worlds'
'Hellos Worlds'
'Jello World'
'Hello Worlded'

如何創建一個搜索詞來查找所有實例,例如

'*ello* World*'

其中star是不一定必須包含在單詞中的通配符。

我找到了 fnmatch 模塊的文檔,但我看不出它如何幫助我搜索文檔。

使用正則表達式並遍歷文件:

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

我通常會選擇正則表達式,但如果出於某種原因你想堅持使用通配符格式,你可以這樣做:

from fnmatch import fnmatch

pattern = '*ello* World*'

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

您描述的 * 語法稱為globbing 它不適用於文檔,僅適用於文件和目錄。 正如其他人所指出的,正則表達式就是答案。

如果您正在做任何復雜的事情,正則表達式是 go 的方法。 如果您對這些不滿意,我認為對於您的具體問題,您也可以使用“in”。 例如:

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

你可以使用正則表達式嗎?

import re
m = re.search('\.*ello', somefile)

更多在這里:

http://docs.python.org/library/re.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM