【发布时间】:2022-01-27 09:17:27
【问题描述】:
有源文件txt(从会计程序下载)和0a,当不需要时(它会换行)。并在需要时在该位置放置 0d 和 0a。我需要在 Excel 中打开它(我还有机会在 csv 中下载它) 当我在xml中下载几乎相同的数据时,我在使用python获取数据时遇到了同样的问题,但我已经解决了
for i in range(1,16):
lstFile.append(str(file))
lstAmount.append(str(amount))
lstKey.append(str(keys[i-1]))
if accPay.find(keys[i-1]) is None:
lstValue.append("none")
else:
lstValue.append(accPay.find(keys[i-1]).text.replace(u'\u000d',' '))
但我不能单独替换 0a。
当我写作时
with open(file, 'r') as file :
filedata = file.read()
filedata = filedata.replace(u'\u000a', ' ')
with open('Konten_last5.txt', 'w') as file:
file.write(filedata)
我将所有 0a 和 0d 0a 替换为 20(空格)。
当我写作时
with open(file, 'r') as file :
filedata = file.read()
filedata = filedata.replace(u'\u000d', ' ')
with open('Konten_last5.txt', 'w') as file:
file.write(filedata)
我尝试单独替换 (u'\u000d\u000a', 'any') 但不起作用,找不到这个组合。
【问题讨论】:
-
应用否定的 Lookbehind。
import re; x='A\u000aB\u000d\u000aC\u000aD'; x; re.sub("(?<!\u000d)\u000a", ' ', x)返回'A\nB\r\nC\nD'和'A B\r\nC D'。请edit 分享您的问题minimal reproducible example - 您如何获取数据(我猜您阅读了csv文件)? -
抱歉还没有完全理解你(如何更改我的代码?我下载 txt。当我下载 csv 时,我在 Excel 中遇到了同样的问题。当我从 xml 中获取我需要的所有数据时文件我有同样的问题,但对于我在范围内(1,16):如果 accPay.find(keys[i-1]) 是 None:lstValue.append("none") else: lstValue.append(accPay.find (keys[i-1]).text.replace(u'\u000d',' ')) 帮助我
-
我几乎抓住了你的想法,但没有意识到))))当有 0a 时我不需要替换 0d...?
-
听起来像是 LF(换行)VS CRLF(回车换行)的问题。前者通常在 *nix 中使用换行符,后者在 Windows 中使用。 txt 文件不知何故将它们混合在一起。为简单起见,您可以尝试一些在线转换器 - app.execeratics.com/LFandCRLFonline/?l=en 或者,您可以使用 JosefZ 的解决方案自己完成。它几乎是单线。只需要在正则表达式(有用的技能)中踮起脚尖
-
尝试了您的解决方案,但得到了相同的结果
标签: python replace unicode txt