gpt4 book ai didi

python - 用空行分隔符分割

转载 作者:太空宇宙 更新时间:2023-11-03 15:23:49 24 4
gpt4 key购买 nike

我在使用空行 "\n\n" 分隔符拆分文本文件时遇到问题。

re.split("\n", aString) 

有效但是

re.split("\n\n", aString) 

只返回整个字符串。

有什么想法吗?

最佳答案

当心line ending conventions of different operating systems !

  • Windows:CRLF (\r\n)
  • Linux 和其他 Unix:LF (\n)
  • 旧 Mac:CR (\r)

您可能会失败,因为您要查找的双换行符位于 Windows 编码的文本文件中,并且将显示为 \r\n\r\n,而不是 \n\n.

repr() 函数将明确告诉您行尾是什么:

>>> mystring = #[[a line of your file]]
>>> repr(mystring)
"'\\nmulti\\nline\\nstring '"

您确定您不想一开始就逐行读取文件吗?

with open(file.txt, 'r') as f:
for line in f:
print (line)

关于python - 用空行分隔符分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10368092/

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