我有一个字符串列表,我需要找出'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
答案 0 :(得分:4)
您可以使用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
答案 1 :(得分:2)
我认为您应该看看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
在列表上圈一下,即可获得想要的东西。
希望这很有帮助
答案 2 :(得分:2)
您可以使用类似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
答案 3 :(得分:2)
使用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)]
答案 4 :(得分:2)
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))
答案 5 :(得分:0)
这可能是另一种方法:
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