The*_*han 4 python wxpython python-2.7 python-3.x python-requests
我从文件中读取,如果找到".",则应"\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()
Run Code Online (Sandbox Code Playgroud)
试试这个(正常方式):
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()
Run Code Online (Sandbox Code Playgroud)
如果您的文本文件不大,您也可以尝试以下方法:
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)
Run Code Online (Sandbox Code Playgroud)
UPDATE(输出新行也取决于您的文本查看器!因为在某些文本编辑器中,“ \ n”是新行,而在另一些文本编辑器中,“ \ r \ n”是新行。):
输入样本:
这是一本书。我喜欢它。
这是一个苹果。我喜欢它。
这是一台笔记本电脑。我喜欢它。
这是一支笔。我喜欢它。
这是手机。我喜欢它。
码:
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()
Run Code Online (Sandbox Code Playgroud)
Ouput将是:
这是一本书。
我喜欢它。
这是一个苹果。
我喜欢它。
这是一台笔记本电脑。
我喜欢它。
这是一支笔。
我喜欢它。
这是手机。
我喜欢它。
| 归档时间: |
|
| 查看次数: |
1076 次 |
| 最近记录: |