在Python中搜索某个单词的位置

2024-05-17 07:33:37 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个字符串,我把它拆分,然后用Python创建了一个列表。你知道吗

我现在需要找到列表中某个单词的位置。你知道吗

我遇到的问题是:我要找的单词在列表中出现了两次。我的代码带回了第一个单词的位置,但是它没有继续,并带回了另一个位置。你知道吗

我踢足球的主要原因是因为我热爱足球。你知道吗

它会找到第一个足球,但不会找到第二个。救命!!你知道吗

这是我的代码:

sentence = " The main reson that i play football is because i love football"
sentence = sentence.split()

print(sentence.index("football"))

Tags: the字符串代码列表playthatismain
3条回答

在下面的代码片段中,我将在列表中包含“football”的索引。你知道吗

s = 'The main reason that i play football is because i love football.'
words = s.split()
i=[ind for ind,p in enumerate(words) if p=='football']
import re

looking_for = 'football'

in_text = 'The main reason that i play football is because i love football.'

without_punctuation = re.sub('[^a-zA-Z ]', '', in_text)
words = without_punctuation.split(' ')

for i, w in enumerate(words):
    if w == looking_for:
        print(i)

但是当然。标点符号将会成为一个问题,就像这里(关于“足球”)一样——所以我现在已经去掉了大部分标点符号。你知道吗

试试这个

def findall(list_in, search_str):
    output=[]
    last_index=0
    while True:
        try:
            find=list_in[last_index:].index(search_str)+last_index
            output.append(find)
            last_index= find+1;
        except:
            break
    return output

输出是一个索引列表,在该列表中可以找到search\u str

相关问题 更多 >