读取每一行并写入到i的结尾

2024-04-24 17:08:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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()

Tags: inposforamsentencewordawesomefeatures
2条回答

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

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

不能写入在“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()

相关问题 更多 >