Skip to main content
 首页 » 编程设计

python之在 Python 中编写函数只保存最后一个字符串 (Python)

2024年10月01日22telwanggs

我在 Python 中使用“nltk”进行 pos 标记,下面的代码在我打印时工作得很好。

import nltk  
import pos_tag 
import nltk.tokenize  
import numpy 
 
f = open(r'C:\Users\sample_data.txt') 
data = f.readlines() 
 
#Parse the text file for NER with POS Tagging 
for line in data: 
    tokens = nltk.word_tokenize(line) 
    tagged = nltk.pos_tag(tokens) 
    #print (tagged) 
 
output = open(r"C:\Users\output3.csv", "w") 
output.write(str(tagged)) 
f.close() 

所以当我打印上面的代码时,输​​出看起来像这样,这正是我想要的。

[('This', 'DT'), ('is', 'VBZ'), ('a', 'DT'), ('simple', 'JJ'), ('sentence', 'NN')] 
[('I', 'PRP'), ('love', 'VBP'), ('this', 'DT'), ('company', 'NN'), ('.', '.'), ('This', 'DT'), ('company', 'NN'), ('is', 'VBZ'), ('so', 'RB'), ('good', 'JJ'), ('.', '.')] 
[('I', 'PRP'), ('am', 'VBP'), ('not', 'RB'), ('inovlved', 'VBN'), ('with', 'IN'), ('this', 'DT'), ('work', 'NN'), ('.', '.'), ('So', 'RB'), ('hard', 'JJ'), ('!', '.')] 
[('What', 'WP'), ('are', 'VBP'), ('you', 'PRP'), ('doing', 'VBG'), ('?', '.'), ('Are', 'NNP'), ('you', 'PRP'), ('nut', 'RB'), ('?', '.')] 
[('Can', 'MD'), ('I', 'PRP'), ('borrow', 'VB'), ('your', 'PRP$'), ('jar', 'NN'), ('?', '.'), ('Just', 'NNP'), ('for', 'IN'), ('today', 'NN'), ('.', '.')] 

但是当我使用代码中的最后三行编写它时,它只保存文本文件中的最后一个字符串(即 [('Can', 'MD'), ('I', 'PRP') , ('借', 'VB'), ('你的', 'PRP$'), ('jar', 'NN'), ('?', '.'), ('只是', 'NNP' ), ('for', 'IN'), ('今天', 'NN'), ('.', '.')]).

我想将整个结果保存在txt或csv文件中,每个[]中的一个字符串应该在txt或csv文件中保存在一行中。

我真的是 Python 的新手,所以非常感谢您的帮助。

请您参考如下方法:

您应该将每一行保存在一个列表中,然后写入整个列表:

tagged_list = [] 
#Parse the text file for NER with POS Tagging 
for line in data: 
    tokens = nltk.word_tokenize(line) 
    tagged_list.append(str(nltk.pos_tag(tokens))) 
 
output = open(r"C:\Users\output3.csv", "w") 
output.write('\n'.join(tagged_list)) 
output.close() 

在 tagged_list 中添加所有要写入的行。使用 '\n'.join(tagged) 编写它们,用 '\n' 分隔(即每个在不同的行中)