【发布时间】:2023-01-03 23:24:02
【问题描述】:
我正在使用 python 3.8。我有 4 个包含文本部分的纯文本文件。我想使用 * 作为分隔符将每个文件分成这些部分的列表,并通过从每个列表中选择一个随机字符串并按给定顺序将它们连接在一起来生成单个文本字符串。它可以工作,除了它有时会从一个或多个文件中生成一个空白字符串。输出应包含每个文件的一段文本,按照代码和文本文件中的 sectionFiles 列表的顺序。
import os
import random
categories = []
result = ''
sourcePath = "C:\\posthelper\\categories\\positive"
os.chdir(sourcePath)
def generate(result):
sectionFiles = ['intro.txt', 'body.txt', 'referral.txt', 'closing.txt']
for item in sectionFiles:
with open(item) as file:
sectionString = file.read()
sectionString = sectionString.replace("\n", "")
sectionStringList = sectionString.split("*")
stringChoice = random.choice(sectionStringList)
result += stringChoice
return(result)
print(generate(result))
--intro.txt--
Hi.*
Hello.*
Yo.*
What up?*
How are you?*
--referral.txt--
This is a referral.*
This is also a referral.*
This is a referral too.*
This is the fourth referral.*
This is The last referral.*
--body.txt--
This is a body.*
This is also a body.*
This is a body too.*
This is the fourth body.*
This is The last body.*
--closing.txt--
Have a good day.*
Bye.*
See yeah.*
Later.*
Later days.*
--wrong output--
This is The last body.This is The last referral.Later.
【问题讨论】:
-
你能提供一些文件样本吗?我认为问题在于,当您拆分字符串时,它会生成一个空字符串
""。这种情况经常发生。一个简单的解决方法是将其更改为sectionString = [word for word in file.read().replace("\n", "").split("*") if word != ""]。看看这是否有效。 -
我之前发布了错误的代码。它已被纠正。
-
一个小技巧——在我看来,
string.strip("\n")比string.replace("\n","")好一点。