首页 > 解决方案 > 读取、编辑,然后将文本 (.txt) 文件保存为列表

问题描述

我是 Python 新手,所以我可以在这里使用很多帮助!我的目标是获取一篇文章并过滤掉所有垃圾词,然后最终将它们导入到 Excel 中,这样我就可以进行一些文本分析。就目前而言,由于大小限制,文章太长而无法复制到单个单元格中。我有以下代码:

article = open(filename, 'w')

letters_only = re.sub("[^a-zA-Z]",  # Search for all non-letters
                          " ",          # Replace all non-letters with spaces
                          str(article))

stop_words = set(stopwords.words('english')) 

# Tokenize the article: tokens
tokens = word_tokenize(letters_only)

# Convert the tokens into lowercase: lower_tokens
lower_tokens = [t.lower() for t in tokens]

# Retain alphabetic words: alpha_only
alpha_only = [t for t in lower_tokens if t.isalpha()]

filtered_sentence = [w for w in alpha_only if not w in stop_words] 

filtered_sentence = [] 

for w in alpha_only: 
    if w not in stop_words: 
        filtered_sentence.append(w)

article.write(str(filtered_sentence))

我遇到的问题是,当我尝试编写文件时,代码基本上会删除所有文本并一无所有地覆盖它。如果有一种更简单的方法可以为机器学习准备一个文件和/或只是剥离一个 stop_words 文件并保存它,我将不胜感激。

标签: pythonpython-3.x

解决方案


您没有提供所有代码,因为在任何地方都没有提到 read,为了帮助您,我们需要更多的上下文。我仍然会尽力为您提供帮助。

如果您从网络加载您的文章,我建议您将其保留为纯字符串(也就是不要将其保存在文件中),将其从不需要的内容中清除,然后保存。

否则,如果您从文件中加载它,您可能更愿意将清理后的文章保存在另一个文件中,然后删除原始文件。它可以防止丢失数据。

在这里,由于 w 标志,您的代码会删除文件的内容,并且不会在其上打印任何内容

'w' -> 将文件截断为零长度或创建用于写入的文本文件。流位于文件的开头。

此外,filtered_sentence 是一个字符串列表,你不能像这样将它转换成一个字符串

article.write(str(filtered_sentence))

您应该执行以下操作

article.write(" ".join(filtered_sentence))

您可以考虑使用 with 语句,它会自动关闭文件,而您似乎没有这样做。

with open(filename, 'w') as article:
    article.write(" ".join(filtered_sentence))

推荐阅读