Python:在元组列表中查找包含特定字符串的单词



我试图在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

最新更新