如何查找列表中元素开头和结尾的单词索引?Python

thr*_*dhn 3 python python-3.x

我有一个字符串列表,我需要找出'American'它是否在该字符串中。如果存在,那么我想找出美国单词的开始和结束索引

\n\n
['Here in Americans, people say \xe2\x80\x9cCan I get a bag for the stuff?\xe2\x80\x9d',\n 'Typically in restaurant after you are done with meal, you ask for check in Americans from the waiter.',\n 'When mixing coffee, people in American use creamer, which is equivalent of milk.']\n
Run Code Online (Sandbox Code Playgroud)\n\n

期望的输出:找出美国单词的开始和结束索引

\n\n
8,16\n75,83\n30,38\n
Run Code Online (Sandbox Code Playgroud)\n

blh*_*ing 5

您可以使用re.search,它返回一个带有start方法的匹配对象,以及一个end返回您要查找的内容的方法:

\n\n
import re\n\nl = [\n    'Here in Americans, people say \xe2\x80\x9cCan I get a bag for the stuff?\xe2\x80\x9d',\n    'Typically in restaurant after you are done with meal, you ask for check in Americans from the waiter.',\n    'When mixing coffee, people in American use creamer, which is equivalent of milk.',\n    'Hello World'\n]\n\nfor string in l:\n    match = re.search('American', string)\n    if match:\n        print('%d,%d' % (match.start(), match.end()))\n    else:\n        print('no match found')\n
Run Code Online (Sandbox Code Playgroud)\n\n

这输出:

\n\n
8,16\n75,83\n30,38\nno match found\n
Run Code Online (Sandbox Code Playgroud)\n