[英]Python: Locate word that contains certain string in list of tuples
我正在嘗試在 python 的列表列表中查找包含特定字符串的單詞,例如:如果我有一個元組列表,例如:
the_list = [
('Had denoting properly @T-jointure you occasion directly raillery'),
('. In said to of poor full be post face snug. Introduced imprudence'),
('see say @T-unpleasing devonshire acceptance son.'),
('Exeter longer @T-wisdom gay nor design age.', 'Am weather to entered norland'),
('no in showing service. Nor repeated speaking', ' shy appetite.'),
('Excited it hastily an pasture @T-it observe.', 'Snug @T-hand how dare here too.')
]
我想找到我搜索的特定字符串並提取包含它的完整單詞,例如
for sentence in the_list:
for word in sentence:
if '@T-' in word:
print(word)
import re
wordSearch = re.compile(r'word')
for x, y in the_list:
if wordSearch.match(x):
print(x)
elif wordSearch.match(y):
print(y)
您可以在您的扁平數組上使用理解列表:
from pandas.core.common import flatten
[[word for word in x.split(' ') if '@T-' in word] for x in list(flatten(the_list)) if '@T-' in x]
#[['@T-jointure'], ['@T-unpleasing'], ['@T-wisdom'], ['@T-it'], ['@T-hand']]
相關地方: 如何從列表列表中制作一個平面列表? (特別是這個答案), Double for 循環列表理解。
你需要使用 re 來完成這個任務
import re
a = re.search("@(.*?)[\s]",'Exeter longer @T-wisdom gay nor design age.')
a.group(0)
注意:您需要考慮 Nonetype 否則它將拋出錯誤
for name in the_list:
try:
if isinstance(name,(list,tuple)):
for name1 in name:
result = re.search("@(.*?)[\s]",name1)
print(result.group(0))
else:
result = re.search("@(.*?)[\s]",name)
print(result.group(0))
except:
pass
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.