Python 2.7 如何在一个文件中插入两个file.txt
我有这个函数,它接受两个input.txt文件,删除标点符号,并添加句子pos或neg。 我想这些fle的内容转换成小写 然后这两个文件合并成一个文件名union.txt 但是我的代码不起作用Python 2.7 如何在一个文件中插入两个file.txt,python-2.7,Python 2.7,我有这个函数,它接受两个input.txt文件,删除标点符号,并添加句子pos或neg。 我想这些fle的内容转换成小写 然后这两个文件合并成一个文件名union.txt 但是我的代码不起作用 def extractor (feature_select): posFeatures = [] negFeatures = [] with open('positive.txt', 'r') as posSentences: for i in posSentences:
def extractor (feature_select):
posFeatures = []
negFeatures = []
with open('positive.txt', 'r') as posSentences:
for i in posSentences:
posWords = re.findall(r"[\w']+|[(,.;:*@#/?!$&)]", i.rstrip())
posWords = [feature_select(posWords), 'pos']
posFeatures.append(posWords)
with open('negative.txt', 'r') as negSentences:
for i in negSentences:
negWords = re.findall(r"[\w']+|[(,.;:*@#/?!$&)]", i.rstrip())
negWords = [feature_select(negWords), 'neg']
negFeatures.append(negWords)
return posFeature, negFeature
filenames = [posFeature, negFeature]
with open('union.txt', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
outfile.write(infile.read())
实际上,您正在尝试打开两个文件内容中的文件名。fname保存从输入文件读取的内容
filenames = [posFeature, negFeature]
with open('union.txt', 'w') as outfile :
for i in filenames : #refers to posFeature or negFeature which is a list
for j in i: #this loop reads each sentence from the list i
outfile.write(j) #it writes the sentence into outfile
无需读回posFeature和negFeature中已经读取和附加的内容。上面的代码将直接在列表文件名中写入内容,现在两个文件合并了