[英]Reading a file and replacing LF, but not CR-LF with python
我在 Windows 上工作,有一堆文本文件,其中一些行以 CRLF 结尾,一些行以 LF 结尾。 我需要做的是用<br>
替换以 LF 结尾的那些,并保持 CRLF 不变。
我尝试过正则表达式(?<!\\\\r)\\\\n
、strip() 和 splitlines(),但 python 总是将 LF 视为 CRLF。
我能做些什么来完成只替换 LF?
谢谢 B。
更新
我再次检查了您的建议,但是它们给了我与我提到的相同的结果 - CRLF 的处理方式与 LF 相同。
我附上了我使用的代码以及示例输入文件和我得到的结果图像。
with open(fileImport) as fp:
testContent = fp.read()
print("**** RESULT 1")
print(testContent)
print(" ")
print("**** RESULT 2")
testContent1 = re.sub(r'(?<!\r)\n', ' <br>', testContent)
print(testContent1)
print(" ")
print("**** RESULT 3")
testContent2 = testContent.replace("\n", "<br>")
print(testContent2)
这就是我使用不同选项得到的结果......
**** RESULT 1
----Row1;TX2829;Text Object;Value1
----Row2;TX2756;Text Object;"= 'Value in row 1: ' &
Num(
Sum(A)/
Sum(B)
, '#.##0 EUR')"
----Row3;CH246;Pivot Table;Title of pivot
**** RESULT 2
----Row1;TX2829;Text Object;Value1 <br>----Row2;TX2756;Text Object;"= 'Value in row 1: ' & <br>Num( <br>Sum(A)/ <br>Sum(B) <br> <br> <br>, '#.##0 EUR')" <br>----Row3;CH246;Pivot Table;Title of pivot <br>
**** RESULT 3
----Row1;TX2829;Text Object;Value1<br>----Row2;TX2756;Text Object;"= 'Value in row 1: ' &<br>Num(<br>Sum(A)/<br>Sum(B)<br><br> <br>, '#.##0 EUR')"<br>----Row3;CH246;Pivot Table;Title of pivot<br>
这就是我需要的
----Row1;TX2829;Text Object;Value1
----Row2;TX2756;Text Object;"= 'Value in row 1: ' &<br>Num(<br>Sum(A)/<br>Sum(B)<br><br> <br>, '#.##0 EUR')"
----Row3;CH246;Pivot Table;Title of pivot
示例文件位于: https : //www.dropbox.com/s/s81dibm8gxsfotf/TEST_FILE.csv?dl=0
预先感谢,B
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.