我正在寻找最清晰,最Pythonic且最快的方法来检查字符串是否包含列表中的单词
这是我到目前为止提出的内容
introStrings = ['introduction:' , 'case:' , 'introduction' , 'case' ]
backgroundStrins = ['literature:' , 'background:', 'Related:' , 'literature' , 'background', 'related' ]
methodStrings = [ 'methods:' , 'method:', 'techniques:', 'methodology:' , 'methods' , 'method', 'techniques', 'methodology' ]
resultStrings = [ 'results:', 'result:', 'experimental:', 'experiments:', 'experiment:', 'results', 'result', 'experimental', 'experiments', 'experiment']
discussioStrings = [ 'discussion:' , 'Limitations:' , 'discussion' , 'limitations']
conclusionStrings = ['conclusion:' , 'conclusions:', 'concluding:' , 'conclusion' , 'conclusions', 'concluding' ]
allStrings = [ introStrings, backgroundStrins, methodStrings, resultStrings, discussioStrings, conclusionStrings ]
testtt = 'this may thod be in techniques ever material and methods'
for item in allStrings:
for word in testtt.split():
if word in item:
print('yes')
break
此代码可以很好地查找所有组合。这是一个嵌套的for循环。乍一看还不清楚。
我想知道是否有更好的方法。
答案 0 :(得分:3)
将any()
与链式列表理解结合使用会更Python化:
print any(word in sublist for word in testtt.split() for sublist in allStrings)
但是这只会返回true / false;它不会识别在哪个子列表中找到哪个词。您可以使用此列表理解来打印特定的匹配项:
print [(word,sublist) for word in testtt.split() for sublist in allStrings if word in sublist]
通过多次计算testtt.split()
,您的代码有点浪费。
答案 1 :(得分:2)
我正在寻找最清晰,最Pythonic且最快的方法来检查字符串是否包含列表中的单词
首先,我将列表弄平
all_strings = [*intro, *back, *methods, ...] # You get the idea
(或者,使用嵌套列表理解)
all_strings = [word for list in [intro, back, ...] for word in list] # if you're into that
接下来,分割字符串:
string_words = a_string.split()
最后,只需查找单词:
found = [w for w in string_words if w in all_strings]
那是非常蟒蛇的,对速度或可靠性不是很确定
答案 2 :(得分:2)
我能得到的是使用chain
和any
:
resultStrings = [
"results:",
"result:",
"experimental:",
"experiments:",
"experiment:",
"results",
"result",
"experimental",
"experiments",
"experiment",
]
conclusionStrings = [
"conclusion:",
"conclusions:",
"concluding:",
"conclusion",
"conclusions",
"concluding",
]
allStrings = [resultStrings, conclusionStrings]
testtt = "this may thod be in techniques ever material and methods"
from itertools import chain
string_set = set(chain(*allStrings))
any(i in string_set for i in testtt.split())
尽管set
需要一些空间,但可以提高效率。谢谢彼得·伍德。
答案 3 :(得分:1)
使用itertools
import itertools
merged = list(itertools.chain.from_iterable(allStrings))
[print(x) for x in testtt.split() if x in merged]