【问题标题】:Python replace 0d in txtPython替换txt中的0d
【发布时间】: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)

我在这两个地方到处都是 0d 0a 请帮忙))

我尝试单独替换 (u'\u000d\u000a', 'any') 但不起作用,找不到这个组合。

尝试了解决方案,但它不起作用..无法在评论中附加图片

【问题讨论】:

  • 应用否定的 Lookbehindimport 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


【解决方案1】:

以二进制模式打开文件 (open(file,'rb'))。然后,您可以读取和处理字节字符串,而不是使用 Unicode 翻译。这在 Windows 上尤其重要,将 '\x0a' 写入文本文件会导致文件系统写入 '\x0d\x0a'

【讨论】:

  • 谢谢!该方法适用于xml,我不明白打开有什么区别,thanx!
  • Traceback(最近一次调用最后):文件“C:\Program Files\Sublime Text 3\replace.py”,第 13 行,在 filedata = filedata.replace('\x0a' , '\x0a') TypeError: a bytes-like object is required, not 'str' I can't use replace?
  • 没关系 filedata = filedata.replace(b'\x0a', b'\x00') 有效
猜你喜欢
  • 2015-11-24
  • 1970-01-01
  • 1970-01-01
  • 2016-03-27
  • 2018-08-29
  • 1970-01-01
  • 1970-01-01
  • 2017-11-08
  • 2011-02-01
相关资源
最近更新 更多