Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以在Python3中将字符串与列表进行比较吗?_Python_Python 3.x - Fatal编程技术网

我可以在Python3中将字符串与列表进行比较吗?

我可以在Python3中将字符串与列表进行比较吗?,python,python-3.x,Python,Python 3.x,我有一个大的文本字符串,我希望搜索某些单词。单词存储在一个列表中。是否有可能(如果有,那么如何)将字符串与列表中的单词进行比较,以便python返回所有找到的单词及其位置,如下所示 text = 'Theres a voice that keeps on calling me. Down the road, thats where Ill always be. Every stop I make, I make a new friend. Cant stay for long, just tur

我有一个大的文本字符串,我希望搜索某些单词。单词存储在一个列表中。是否有可能(如果有,那么如何)将字符串与列表中的单词进行比较,以便python返回所有找到的单词及其位置,如下所示

text = 'Theres a voice that keeps on calling me. Down the road, thats where Ill always be. Every stop I make, I make a new friend. Cant stay for long, just turn around and Im gone again. Maybe tomorrow, Ill want to settle down, Until tomorrow, I’ll just keep moving on.'

search_list = ['voice', 'Until', 'gone']

print(compare(text, search_list))

#returns something like: {voice: 11, Until: 112, gone: 54}
#p.s. the locations are random since I couldn't be bothered to count the characters
#but the format is something like {found_term: position of first character} 
#(compare doesn't necessarily have to return the results in dictionary format)
我尝试过在stack overflow和google上搜索,但大多数类似的问题都是关于比较两个字符串或两个列表

提前谢谢。

您可以对字符串使用
.index()
来获取子字符串的位置:

from typing import List, Dict


def compare(text: str, search_list: List[str]) -> Dict[str, int]:
    return {
        word: text.index(word)
        for word in search_list  
    }

使用
str.index
&循环如果文本中有多个该单词的实例,该怎么办?例如,如果单词voice在文本中出现2次或3次,输出应该是什么?它是否应该在列表中输出其所有位置?它应该是第一个位置还是最后一个位置?
{word:text.find(word)for word in search_list if word in text}
?欢迎使用堆栈溢出!请拿起,阅读,和,并提供一个。“为我实现此功能”是本网站的主题。你必须做出诚实的尝试,然后问一个关于你的算法或技术的具体问题。