搜索一个字符串是否包含基于列表的另一个字符串的最快方法是什么?
这个很好用,但是当字符串很大且列表很长时,对于我来说太慢了。
test_string = "Hello! This is a test. I love to eat apples."
fruits = ['apples', 'oranges', 'bananas']
for fruit in fruits:
if fruit in test_string:
print(fruit+" contains in the string")
Run Code Online (Sandbox Code Playgroud)
为此,我建议首先用标记该字符串,RegexpTokenizer以删除所有特殊字符,然后使用它sets来找到交集:
from nltk.tokenize import RegexpTokenizer
test_string = "Hello! This is a test. I love to eat apples."
tokenizer = RegexpTokenizer(r'\w+')
test_set = set(tokenizer.tokenize(test_string))
# {'Hello', 'I', 'This', 'a', 'apples', 'eat', 'is', 'love', 'test', 'to'}
Run Code Online (Sandbox Code Playgroud)
在标记了字符串并构造了一个集合之后,找到了set.intersection:
set(['apples', 'oranges', 'bananas']) & test_set
# {'apples'}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
221 次 |
| 最近记录: |