标记字符串列表以返回单词标记列表

时间:2019-03-17 04:03:32

标签: python string list nlp tokenize

美好的一天,

我有一个应该具有降低和标记文本并返回标记的功能。 这是下面的功能:

def preprocess_text(text):
""" A function to lower and tokenize text data """ 
# Lower the text
lower_text = text.lower()

# tokenize the text into a list of words
 tokens = nltk.tokenize.word_tokenize(lower_text)

return tokens

然后,我希望将该函数应用于实际的文本数据data,该数据是其中包含字符串的列表。我想遍历data中的每个字符串,并应用该函数来降低和标记化文本数据。

最后,我希望将标记词添加到称为tokenized_final的最终列表中,该列表应该是包含标记词的最终列表。 以下是下面的代码:

# Final list with tokenized words
tokenized_final = []

# Iterating over each string in data
for x in data:
    # Calliing preprocess text function
    token = preprocess_text(x)

    tokenized_final.append(token)  

但是,当我执行所有这些操作并打印列表tokenized_final时。它输出一个大列表,其中包含列表。

print (tokeninized_final)

Output:
 [['pfe', 'bulls', 'have', 'reasons', 'on'],
 ['to', 'pay', 'more', 'attention'],
 ['there', 'is', 'still']]

当我期望的tokenized_final输出在以下一个列表中时:

['pfe', 'bulls', 'have', 'reasons', 'on','to', 'pay','more', 'attention','there','is', 'still']

是否有任何方法可以纠正预处理功能并将其应用于数据以获得所需的输出。还是有什么办法可以做到这一点? 帮助将在此不胜感激。 预先感谢

1 个答案:

答案 0 :(得分:1)

您只需要拼合结果列表:

# Final list with tokenized words
tokenized_final = []

# Iterating over each string in data
for x in data:
    # Calliing preprocess text function
    token = preprocess_text(x)

    tokenized_final.append(token) 

flattened_tokeninized_final = [i for j in tokeninized_final for i in j]
相关问题