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



我有字符串列表,我需要找出'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 方法的 match 对象和一个返回您要查找的内容的 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
您可以使用

类似 str.find(search_item)

这将返回搜索项出现的第一个索引值,然后您可以只返回index + len(search_item)

像这样:

string = "Hello world!"
search_item = "world"
search_index = string.find(search_item)
search_index_end = search_index+len(search_item)
print(string[search_index] : search_index_end])

输出:

world
search_index = 6
search_index_end = 11
我认为

你应该看看str.find方法:https://docs.python.org/3/library/stdtypes.html#str.find

例:

>>> str1 = 'Here in Americans, people say "Can I get a bag for the stuff?"'
>>> str2 = "Americans"
>>> print(str1.find(str2))
8

循环查看您的列表以获得您想要的东西。

希望这是有帮助的

使用 re 和列表理解。灵感来自@blhsing的解决方案

import re
a=['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.']
regex  = re.compile('American')
[(match.start(), match.end())  for i in a for match in regex.finditer(i)]
string=['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.']
string2="American"
for sentence in string:
    initial=int(sentence.find(string2))
    end_point=initial+len(string2)
    print ("%d,%d"%(initial,end_point))

这可能是另一种方法:

all_data = ['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.']

for data in all_data:
    words = data.split(' ')
    counter = 0
    for position, word in enumerate(words):
        if 'American' in word:
            print('{}, {}'.format(counter, counter+8))
        else:
            counter += len(word) + 1

最新更新