【问题标题】:Removing all spaces in text file with Python 3.x使用 Python 3.x 删除文本文件中的所有空格
【发布时间】:2017-04-17 07:34:01
【问题描述】:

所以我的爬虫制作了这个疯狂的长文本文件,它出于某种原因在链接之间添加了一些空格,如下所示:

https://example.com/asdf.html                                (note the spaces)
https://example.com/johndoe.php                              (again)

我想摆脱它,但保留新行。请记住,文本文件有 4.000 多行。我尝试自己做,但发现我不知道如何遍历文件中的新行。

【问题讨论】:

  • 遍历行:for line in open('file.txt'): 试试这个,看看你能走多远(解决实际问题)。

标签: python web-crawler


【解决方案1】:

好像你不能直接编辑python文件,所以这是我的建议:

# first get all lines from file
with open('file.txt', 'r') as f:
    lines = f.readlines()

# remove spaces
lines = [line.replace(' ', '') for line in lines]

# finally, write lines in the file
with open('file.txt', 'w') as f:
    f.writelines(lines)

【讨论】:

  • 第 3 行,在 中 data = f.readlines() 文件“C:\Python34\lib\encodings\cp1250.py”,第 23 行,在解码中返回 codecs.charmap_decode(input, self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 1357: character maps to 该“位置”是指字符位置还是文本文件中的行?
  • 如果您的文件中有 unicode 字符,请执行以下操作:with open('file.txt', 'r', encoding="utf8")
【解决方案2】:

您可以打开文件并逐行读取并删除空格 -

Python 3.x:

with open('filename') as f:
    for line in f:
        print(line.strip())

Python 2.x:

with open('filename') as f:
    for line in f:
        print line.strip()

它将删除每一行的空格并打印出来。

希望对你有帮助!

【讨论】:

  • 由于某种原因,这似乎不适用于我的 python 版本
  • @Kappa,我猜你正在使用 python2.x。请将print(line.strip()) 更改为print line.strip()。它会起作用的。
  • @OmPrakash 实际上括号在 2.x 中没有任何区别,并且 OP 在问题中明确提到了 3.x。
  • @Kappa 你能扩展一下“似乎不起作用”吗?
  • @Om Prakash 我使用的是 3.4.3,不,错误是:行继续字符后出现意外字符。它突出显示with open('filename') as f:之后的区域
【解决方案3】:

从文件中读取文本,删除空格,将文本写入文件:

with open('file.txt', 'r') as f:
    txt = f.read().replace(' ', '')

with open('file.txt', 'w') as f:
    f.write(txt)

在@Leonardo Chirivì 的解决方案中,当字符串足够且内存效率更高时,无需创建列表来存储文件内容。 .replace(' ', '') 操作只在字符串上调用一次,这比遍历列表对每一行单独执行替换更有效。

为避免打开文件两次:

with open('file.txt', 'r+') as f:
    txt = f.read().replace(' ', '')
    f.seek(0)
    f.write(txt)
    f.truncate()

只打开一次文件会更有效率。这需要在读取后将文件指针移回文件的开头,并在写回文件后截断任何可能剩余的内容。然而,这个解决方案的一个缺点是不那么容易阅读。

【讨论】:

  • 你能解释一下与其他答案有什么不同吗?
  • @MuhammadDyasYaskur 我更新了我的答案以包含更多解释。谢谢
【解决方案4】:

我遇到过类似的事情。

这对我有用(注意:这会将 2+ 个空格转换为逗号,但如果您阅读下面的代码块,我将解释如何摆脱所有空格):

import re

# read the file
with open('C:\\path\\to\\test_file.txt') as f:
    read_file = f.read()
    print(type(read_file)) # to confirm that it's a string

read_file = re.sub(r'\s{2,}', ',', read_file) # find/convert 2+ whitespace into ','

# write the file
with open('C:\\path\\to\\test_file.txt', 'w') as f:
    f.writelines('read_file')

这帮助我将更新后的数据发送到 CSV,这适合我的需要,但它也可以为您提供帮助,因此您可以将其转换为空的,而不是将其转换为逗号 (',')字符串 (''),然后 [或] 如果您根本不需要任何空格,请使用 read_file.replace(' ', '') 方法。

【讨论】:

    猜你喜欢
    • 2011-10-01
    • 1970-01-01
    • 2010-12-08
    • 2011-05-05
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    相关资源
    最近更新 更多