阅读每一行并写到最后

时间:2018-05-24 16:17:31

标签: python python-3.x

我是python的新手,如果我问一个非常简单的问题,请原谅。

我正在尝试从文本文件中读取每一行并预测每行的情绪并将输出写入文本文件的末尾。为此,我试图将数据附加到行的末尾。

我的文字文件如下所示:

I am awesome.
I am terrible.
I am bad.

我想要实现的目标如下:

I am awesome. - Positive
I am terrible. - Negative
I am bad. - Negative

运行代码时,文件将保存为空。请帮忙。

我的代码如下:

import nltk.classify.util
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import names


def word_feats(words):
    return dict([(word, True) for word in words])


positive_vocab = ['awesome', 'outstanding', 'fantastic', 'terrific', 'good', 'nice', 'great', ':)']
negative_vocab = ['bad', 'terrible', 'useless', 'hate', ':(']

positive_features = [(word_feats(pos), 'pos') for pos in positive_vocab]
negative_features = [(word_feats(neg), 'neg') for neg in negative_vocab]

train_set = negative_features + positive_features

classifier = NaiveBayesClassifier.train(train_set)

# Predict
neg = 0
pos = 0

f = open("test.txt", "r")
for sentence in f.readlines():
    sentence = sentence.lower()
    words = sentence.split(' ')
    for word in words:
        classResult = classifier.classify(word_feats(word))
        if classResult == 'neg':
            f.write(' negative')
        if classResult == 'pos':
            f.write(' positive')

f.close()

2 个答案:

答案 0 :(得分:2)

您无法写入以'r'模式打开的文件 - 该模式用于阅读。

我的建议是打开文件进行阅读,然后打开第二个文件并写出来。如下所示:

f = open("test.txt", "r")
out_file = open("output.txt", "w")
for sentence in f.readlines():
    orig = sentence
    sentence = sentence.lower()
    words = sentence.split(' ')
    for word in words:
        classResult = classifier.classify(word_feats(word))
        if classResult == 'neg':
            out_file.write(orig + ' negative')
        if classResult == 'pos':
            out_file.write(orig + ' positive')

f.close()
out_file.close()

答案 1 :(得分:-3)

您正在以读取模式打开文件。您需要以写入方式打开该文件。

f = open('test.txt', 'w')