我有一个字符串列表,我需要找出 'American'
是否在该字符串中。如果它存在,那么我想找出美国单词的开始和结束索引
['Here in Americans, people say “Can I get a bag for the stuff?”',
'Typically in restaurant after you are done with meal, you ask for check in Americans from the waiter.',
'When mixing coffee, people in American use creamer, which is equivalent of milk.']
期望的输出:找出美国单词的开始和结束索引
8,16
75,83
30,38
最佳答案
您可以使用 re.search
,它会返回一个匹配对象,其中包含一个 start
方法和一个 end
方法,返回您想要的内容寻找:
import re
l = [
'Here in Americans, people say “Can I get a bag for the stuff?”',
'Typically in restaurant after you are done with meal, you ask for check in Americans from the waiter.',
'When mixing coffee, people in American use creamer, which is equivalent of milk.',
'Hello World'
]
for string in l:
match = re.search('American', string)
if match:
print('%d,%d' % (match.start(), match.end()))
else:
print('no match found')
这个输出:
8,16
75,83
30,38
no match found
关于python - 如何找到列表中元素开始和结束的单词索引? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54539892/