我有一个包含一些要打开和阅读的文件的文件夹,分别从它们中提取一些波斯语单词并加入每组单词来制作一个句子。最后,我想将每个句子保存到一个单独的.txt文件中。但问题是最后一句保存在所有文件中。我该怎么解决?
import os
import codecs
###opening the files from a folder in a directory
matches=[]
for root, dirs, files in os.walk("C:\\Users\\Maryam\\Desktop\\New Folder"):
for file in files:
if file.endswith(".pts"):
matches.append(os.path.join(root, file))
print(matches)
print(len(matches))
###reading files
for f in matches:
with codecs.open(f, "r", "utf-8") as fp:
text=fp.read().split('\n')
#print(text)
#print (len(text))
###converts one string to strings
for line in text:
line_list=line.split()
#print (line_list)
###extracting the persian words and removing the parantheses
list_persian_letters=['ا','آ', 'ب','پ','ت','ث','ج','چ','ح','خ','د','ذ','ر','ز','ژ','س','ش','ص','ض','ط','ظ','ع','غ','ف','ق','ک','گ','ل','م','ن','و','ه','ی','.','؟','،',':','!']
output_words = [word for word in line_list if (word[0] in list_persian_letters)]
output=[s.replace(')', '') for s in output_words]
#print (output)
###joining the words as as sentence
sentence=' '.join(output)
###saving each sentence in a separate file
for i in range(1,16):
with codecs.open ("F:\\New folder\\output%i.txt" %i, "w","utf-8") as text_file:
text_file.writelines(sentence)
答案 0 :(得分:2)
在每次循环迭代中都会覆盖所有文件。所以你只看到最后一次迭代的结果。
将外循环更改为:
<?=form_open_multipart('Admin/add_news',['class'=>'form'],['aid'=>$this->session->userdata('adminId')])?>
和
for i, f in enumerate(matches):
并摆脱1..16循环:
for j, line in enumerate(text):
并修改:
for i in range(1,16):
我希望您能更改代码以获得您想要的内容。