我有一个字符串列表,我需要找出'American'它是否在该字符串中。如果存在,那么我想找出美国单词的开始和结束索引
['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.']\nRun Code Online (Sandbox Code Playgroud)\n\n期望的输出:找出美国单词的开始和结束索引
\n\n8,16\n75,83\n30,38\nRun Code Online (Sandbox Code Playgroud)\n
您可以使用re.search,它返回一个带有start方法的匹配对象,以及一个end返回您要查找的内容的方法:
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')\nRun Code Online (Sandbox Code Playgroud)\n\n这输出:
\n\n8,16\n75,83\n30,38\nno match found\nRun Code Online (Sandbox Code Playgroud)\n