gpt4 book ai didi

python - 用换行符替换一些特殊字符\n

转载 作者:行者123 更新时间:2023-12-01 05:27:01 30 4
gpt4 key购买 nike

我有一个包含数字和符号的文本文件,我想删除其中的一些字符并添加新行。例如文本文件是这样的:

00004430474314-3","100004430474314-3","1779803519-3","100003004929477-3","100006224433874-3","1512754498-3","100003323786067

我希望输出是这样的:

00004430474314
100004430474314
100003004929477
1779803519
100006224433874
1512754498
100003323786067

我尝试用此代码替换 -3","\n 但它不起作用。有什么帮助吗?

import re
import collections
s = re.findall('\w+', open('text.txt').read().lower())
print(s.replace("-3","",">\n"))

最佳答案

re.findall 在这里没用。

with open('path/to/file') as infile:
contents = infile.read()
contents = contents.replace('-3","', '\n')
print(contents)

您的代码的另一个问题是您似乎认为 "-3","" 是包含 -3"," 的字符串。不是这种情况。 Python 看到第二个 " 并将其解释为字符串的结尾。后面有一个逗号,这使得 python 将第二位视为 s.replace()< 的第二个参数.

你真正想做的是告诉 python 这些双引号是字符串的一部分。您可以通过手动转义它们来完成此操作,如下所示:

some_string_with_double_quotes = "this is a \"double quote\" within a string"

您还可以通过用单引号定义字符串来完成同样的事情:

some_string_with_double_quotes = 'this is a "double quote" within a string'

这两种类型的引号在 python 中是等效的,都可以用来定义字符串。如果您来自 C++ 这样的语言,这对您来说可能会很奇怪,其中单引号用于字符,双引号用于字符串。

关于python - 用换行符替换一些特殊字符\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21128781/

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