【发布时间】:2018-04-03 18:06:49
【问题描述】:
我正在尝试打开一个文本文件,删除某些后面有 ] 的单词,然后将新内容写入一个新文件。使用以下代码,new_content 包含我需要的内容,并创建了一个新文件,但它是空的。我不知道为什么。我尝试过不同的缩进并传入编码类型,但没有成功。非常感谢任何帮助。
import glob
import os
import nltk, re, pprint
from nltk import word_tokenize, sent_tokenize
import pandas
import string
import collections
path = "/pathtofiles"
for file in glob.glob(os.path.join(path, '*.txt')):
if file.endswith(".txt"):
f = open(file, 'r')
flines = f.readlines()
for line in flines:
content = line.split()
for word in content:
if word.endswith(']'):
content.remove(word)
new_content = ' '.join(content)
f2 = open((file.rsplit( ".", 1 )[ 0 ] ) + "_preprocessed.txt", "w")
f2.write(new_content)
f.close
【问题讨论】:
-
for word in content: if word.endswith(']'): content.remove(word)在迭代时被删除:bad -
f.close什么都不做,缩进是错误的。 -
if file.endswith(".txt")保证始终为真,因为您执行了 globbing。 -
你根本没有关闭
f2 -
您应该使用模式'a'打开文件进行写入。请参阅:docs.python.org/3/library/functions.html#open。或者做一个单词列表,然后使用
writelines