Skip to main content
 首页 » 编程设计

Python之分组顺序数组成员

2025年04月02日16emanlee

我想像这样编辑我的文本:

arr = []  
# arr is full of tokenized words from my text 

例如:

"Abraham Lincoln Hotel is very beautiful place and i want to go there with 
 Barbara Palvin. Also there are stores like Adidas ,Nike , Reebok." 

编辑:基本上我想检测专有名称并通过在 for 语句中使用 istitle() 和 isAlpha() 对它们进行分组,例如:

for i in arr: 
    if arr[i].istitle() and arr[i].isAlpha 

在这个例子中,arr 一直追加到下一个单词的第一个字母不是大写。

arr[0] + arr[1] + arr[2] = arr[0] 
#Abraham Lincoln Hotel 

这就是我想要的新 arr:

['Abraham Lincoln Hotel'] 是一个非常美丽的地方,我想去那里 ['Barbara Palvin']。 ['Also'] 还有 ['Adidas']、['Nike'] 等商店 ['Reebok'].

“Also”对我来说不是问题,当我尝试与我的数据集匹配时它会很有用。

请您参考如下方法:

你可以这样做:

sentence = "Abraham Lincoln Hotel is very beautiful place and i want to go there with Barbara Palvin. Also there are stores like Adidas, Nike, Reebok." 
all_words = sentence.split() 
last_word_index = -100 
proper_nouns = [] 
for idx, word in enumerate(all_words): 
    if(word.istitle() and word.isalpha()): 
        if(last_word_index == idx-1): 
            proper_nouns[-1] = proper_nouns[-1] + " " + word 
        else: 
            proper_nouns.append(word) 
        last_word_index = idx 
print(proper_nouns) 

此代码将:

  • 将所有单词拆分成一个列表
  • 遍历所有单词和
    • 如果最后一个大写的单词是前一个单词,它将把它附加到列表中的最后一个条目
    • 否则它将把这个单词存储为列表中的一个新条目
    • 记录最后一次找到大写单词的索引