python - 如何找到列表中元素开始和结束的单词索引? Python

标签 python python-3.x

我有一个字符串列表,我需要找出 '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/

相关文章:

python - 如何使用 Sympy 使用我设计的唯一变量符号求解方程

Python:如何根据其表示进行除法?

Python dataframes - 如何在此处应用线程/多重处理来加快速度

python - QueryParser.parse,限制单词之间的距离

Mac OSX 中的 Python 启动器首选项不允许选择 python 3.6 解释器

python-3.x - 如何从pandas表中获取每个值的百分比?

python - Pandas :为无值设置默认日期时间

Python Pandas isin 返回索引

python - 如何在不必编写 20 个 if 语句或制作 20 个列表/字典的情况下进行以下比较?

python - 无法使用基于 python 的库 ftplib 连接到本地 FTP 服务器