Python-从文本文件中删除所有“

时间:2018-11-04 22:03:11

标签: python syntax

我有一个包含以下数据的文本文件:

't''h''i''s''i''s''a''t''e''s''t''f''o''r''s''t''a''c''k''o''v''e''r''f''l''o''w'

我想读取文件,然后删除所有',这样最终结果将如下所示:

thisisatestforstackoverflow

我不知道您是否需要写入另一个文件,也可以只更改当前文件,但是我尝试使用replace()进行操作,但无法正常工作。如果有人可以写一点和平的代码来告诉我它是如何工作的,我将不胜感激!

3 个答案:

答案 0 :(得分:3)

我喜欢具有以下实用程序功能:

def string_to_file(string, path):
    with open(path, 'w') as f:
        f.write(string)


def file_to_string(path):
    with open(path, 'r') as f:
        return f.read()

有了这些,答案就变成了:

string_to_file(file_to_string(path).replace("'", ""), path)

答案 1 :(得分:1)

import re 
string = 't''h''i''s''i''s''a''t''e''s''t''f''o''r''s''t''a''c''k''o''v''e''r''f''l''o''w'
s = re.findall(r"[^']", string)

这将返回一个列表:

C:\Users\Documents>py test.py
['t', 'h', 'i', 's', 'i', 's', 'a', 't', 'e', 's', 't', 'f', 'o', 'r', 's', 't', 'a', 'c', 'k', 'o', 'v', 'e', 'r', 'f', 'l', 'o', 'w']

您可以用它做任何事。
喜欢:

''.join(s)

输出:

C:\Users\Documents>py test.py
thisisatestforstackoverflow

答案 2 :(得分:0)

您在这里回答:

str = 't''h''i''s''i''s''a''t''e''s''t''f''o''r''s''t''a''c''k''o''v''e''r''f''l''o''w'
str.replace("'", "")
print(str)