我有一个文件,其中一些句子分布在多行中。 例如:
1:1 This is a simple sentence
[NEWLINE]
1:2 This line is spread over
multiple lines and it goes on
and on.
[NEWLINE]
1:3 This is a line spread over
two lines
[NEWLINE]
所以我希望它看起来像这样
1:1 This is a simple sentence
[NEWLINE]
1:2 This line is spread over multiple lines and it goes on and on.
[NEWLINE]
1:3 This is a line spread over two lines
有些行跨越 2、3 或 4 行。如果后面的所有行不是新行,则应将其合并为一行。 我想覆盖给定的文件以创建一个新文件。
我已经尝试过 while 循环,但没有成功。
input = open(file, "r")
zin = ""
lines = input.readlines()
#Makes array with the lines
for i in lines:
while i != "\n"
zin += i
.....
但这会造成无限循环。
最佳答案
您不应在用例中嵌套 for
和 while
循环。代码中发生的情况是,for
循环将一行分配给变量 i
,但它没有被嵌套的 while
修改。 code> 循环,因此如果 while
子句为 True
,那么它将保持这种状态,并且没有中断条件,最终会出现无限循环。
解决方案可能如下所示:
single_lines = []
current = []
for i in lines:
i = i.strip()
if i:
current.append(i)
else:
if not current:
continue # treat multiple blank lines as one
single_lines.append(' '.join(current))
current = []
else:
if current:
# collect the last line if the file doesn't end with a blank line
single_lines.append(' '.join(current))
覆盖输入文件的好方法是收集内存中的所有输出,在读出文件后关闭文件并重新打开它进行写入,或者在读取输入时写入另一个文件并重命名第二个文件以覆盖关闭两者后的第一个。
关于python - 如果文件中的行不为空,则将行连接在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35919381/