簡體   English   中英

如何使用僅代表單個單詞而不代表多個單詞的通配符在 Python 中搜索字符串?

[英]How to search strings in Python using a wildcard that represents only a single word -- and not multiple words as well?

fnmatch 在 Python 中非常簡單——但是它會 output “真”,無論是在你放置通配符的單詞之間有 1 個還是 100 個單詞。

我想比這更窄——並且能夠使用某種通配符搜索庫,讓我指定我想成為通配符的單詞數量。

因此,如果我使用:“the * cat”,它只會包含單個詞,例如“the ugly cat”或“the furry cat”

但是,如果我使用類似“the ** cat”的詞,它只會包含兩個詞,例如“the very ugly cat”或“the extremely fury cat”

是否有任何 python 庫允許這種微調通配符功能?

謝謝!

首先,顯而易見的解決方法是在通配符之間放置一個空格,如果這是您的意思的話。

其次,通配符也匹配空格,意思不一樣就得說不一樣。

匹配“單詞”的正則表達式是\w+因此您可以將代碼重新表述為

import re

for match in re.findall(r"the \w+ \w+ cat", text):
    print(match)

如果你想支持*通配符並且只匹配文字文本,請嘗試類似

pattern = "the * * cat"
regex = '\w+'.join(re.escape(fragment) for fragment in pattern.split('*'))
for match in re.findall(regex, text):
    print(match)

暫無
暫無

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

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