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

2024-04-26 07:56:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件夹,包括一些文件打开和阅读,提取一些波斯语单词从他们分开,并加入每一个词集,使一个句子。最后,我想将每个句子保存到一个单独的.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)

Tags: 文件thetextinforoutputasline
1条回答
网友
1楼 · 发布于 2024-04-26 07:56:32

在每个循环迭代中,所有文件都被覆盖。所以你只能看到最后一次迭代的结果。你知道吗

将外循环更改为:

for i, f in enumerate(matches):

以及

for j, line in enumerate(text):

摆脱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:

我希望你能修改代码以得到你想要的。你知道吗

相关问题 更多 >