gpt4 book ai didi

python - 在文本文件中查找一个点并在 Python 中向该文件添加一个换行符?

转载 作者:太空狗 更新时间:2023-10-30 02:38:22 25 4
gpt4 key购买 nike

我从一个文件中读取,如果它找到一个 ".",它应该在文本中添加一个换行符 "\n" 并将其写回文件.我试过这段代码,但问题仍然存在。

inp = open('rawCorpus.txt', 'r')
out = open("testFile.text", "w")

for line in iter(inp):
l = line.split()
if l.endswith(".")
out.write("\n")
s = '\n'.join(l)
print(s)
out.write(str(s))
inp.close()
out.close()

最佳答案

试试这个(正常方式):

with open("rawCorpus.txt", 'r') as read_file:
raw_data = read_file.readlines()


my_save_data = open("testFile.text", "a")

for lines in raw_data:

if "." in lines:

re_lines = lines.replace(".", ".\r\n")
my_save_data.write(re_lines)

else:
my_save_data.write(lines + "\n")

my_save_data.close()

如果你的文本文件不大,你也可以试试这个:

with open("rawCorpus.txt", 'r') as read_file:
raw_data = read_file.read()

re_data = raw_data.replace(".", ".\n")

with open("testFile.text", "w") as save_data:
save_data.write(re_data)

UPDATE ( 输出新行也取决于您的文本查看器!因为在某些文本编辑器中“\n”是新行,而在其他一些文本编辑器中“\r\n”是新行。 ):

输入样本:

This is a book. i love it.

This is a apple. i love it.

This is a laptop. i love it.

This is a pen. i love it.

This is a mobile. i love it.

代码:

last_buffer = []
read_lines = [line.rstrip('\n') for line in open('input.txt')]

my_save_data = open("output.txt", "a")


for lines in read_lines:

re_make_lines = lines.split(".")

for items in re_make_lines:

if items.replace(" ", "") == "":
pass

else:

result = items.strip() + ".\r\n"
my_save_data.write(result)

my_save_data.close()

输出将是:

This is a book.

i love it.

This is a apple.

i love it.

This is a laptop.

i love it.

This is a pen.

i love it.

This is a mobile.

i love it.

关于python - 在文本文件中查找一个点并在 Python 中向该文件添加一个换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47241845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com