Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将每个字符串保存到单独的文件中?_Python_Python 3.x - Fatal编程技术网

Python 如何将每个字符串保存到单独的文件中?

Python 如何将每个字符串保存到单独的文件中?,python,python-3.x,Python,Python 3.x,我有一个文件夹,里面有一些要打开和阅读的文件,分别从中提取一些波斯语单词,并将每一组单词组合成一个句子。最后,我想将每个句子保存到一个单独的.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\\Desk

我有一个文件夹,里面有一些要打开和阅读的文件,分别从中提取一些波斯语单词,并将每一组单词组合成一个句子。最后,我想将每个句子保存到一个单独的.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)

在每次循环迭代中都会覆盖所有文件。因此,您只能看到最后一次迭代的结果

将外部循环更改为:

for i, f in enumerate(matches):

然后去掉1..16循环:

for i in range(1,16):
并修改:

with codecs.open ("F:\\New folder\\output%i_%i.txt" % (i,j), "w","utf-8") as text_file:

我希望您能更改代码以获得您想要的内容。

旁白:您可以使用
列出波斯语字母=“ABCDE…”
而不是
列出波斯语字母=['A'、'B'、'C'、'D'、'E'、…]
,因为字符串是一个序列。
with codecs.open ("F:\\New folder\\output%i_%i.txt" % (i,j), "w","utf-8") as text_file: