在Python中编写函数仅保存最后一个字符串(Python) [英] Writing function in Python saves only the last string (Python)

查看:52
本文介绍了在Python中编写函数仅保存最后一个字符串(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中使用‘nltk’进行位置标记,下面的代码在我打印它时工作得非常好。

import nltk 
import pos_tag
import nltk.tokenize 
import numpy

f = open(r'C:Userssample_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:Usersoutput3.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’),(‘Borrow’,‘VB’),(‘Your’,‘PRP$’),(‘JAR’,‘NN’),(‘?’,‘.),(’Just‘,’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:Usersoutput3.csv", "w")
output.write('
'.join(tagged_list))
output.close()
tagged_list中添加要编写的所有行。使用' '.join(tagged)编写它们,用‘ ‘(即每个都在不同的行)

这篇关于在Python中编写函数仅保存最后一个字符串(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆