繁体   English   中英

字符串中短语之前的前序单词数

[英]Number of preceeding words before a phrase in a string

假设我有一个短语列表:

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

知道我怎样才能有效地做到这一点吗?

幼稚的方法,不考虑任何性能或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}

使用countindex

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 ,直到遇到词组的首次出现为止, count计算text空格,该空格与该词组前面的单词数相同。

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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM