Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用换行符替换某些特殊字符\n_Python - Fatal编程技术网

Python 用换行符替换某些特殊字符\n

Python 用换行符替换某些特殊字符\n,python,Python,我有一个包含数字和符号的文本文件,我想删除其中的一些字符,并添加新行。 例如,文本文件如下所示: 00004430474314-3","100004430474314-3","1779803519-3","100003004929477-3","100006224433874-3","1512754498-3","100003323786067 00004430474314 100004430474314 100003004929477 1779803519 100006224433874 1

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

00004430474314-3","100004430474314-3","1779803519-3","100003004929477-3","100006224433874-3","1512754498-3","100003323786067
00004430474314
100004430474314
100003004929477
1779803519
100006224433874
1512754498
100003323786067
我希望输出是这样的:

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.RePuffE()/<代码> < /P> 您真正想要做的是告诉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++之类的语言,这对你来说很奇怪,其中单引号用于字符,双引号用于字符串。

< P>首先,我认为S对象不是一个字符串,而是一个列表,如果你尝试使它成为一个字符串(S=’‘联接(s))。例如)您将以以下内容结束:

0000443047431431000044304743143177980351931000030049294773100006224433874315127544983100003323786067
其中replace()是无用的

我将您的代码更改为以下内容(在python 3.2中测试)


这不需要Python,任何文本编辑器都可以像这样轻松地进行简单的查找和替换。