假设我有一个短语列表:
list = ['new york', 'school', 'new']
和一个字符串
text = 'i am going to a school in new york and therefore i have to buy a new uniform to go to new york'
我想找到每个短语之前的单词数量(仅针对首次出现),即输出应为:
new york = 7
school = 5
new = 7
有什么想法可以有效地实现这一目标吗?
答案 0 :(得分:0)
天真的方法,不考虑任何性能或NLP:
lst = ['new york', 'school', 'new'] # do not use 'list' as a name
text = 'i am going to a school in new york and therefore i have to buy a new uniform to go to new york'
{p: len(text[:text.find(p)].strip().split()) for p in lst}
# {'new york': 7, 'school': 5, 'new': 7}
答案 1 :(得分:0)
使用count
和index
:
lst = ['new york', 'school', 'new']
text = 'i am going to a school in new york and therefore i have to buy a new uniform to go to new york'
for x in lst:
print(f"{x} = {text.count(' ', 0, text.index(x))}")
# new york = 7
# school = 5
# new = 7
count
从开始算起text
中的空格,直到遇到与该短语之前的单词数量相同的短语为止。
答案 2 :(得分:0)
lst = ['new york', 'school', 'new']
text = 'i am going to a school in new york and therefore i have to buy a new uniform to go to new york'
这将为您提供要搜索其计数和字符串数的字符串
for x in lst:
print(x +": "+str(len(text[0:text.index(x)].split(' ')) -1))