【问题标题】:Removing whitespace and carriage return from a text file with Python使用 Python 从文本文件中删除空格和回车符
【发布时间】:2021-08-28 08:01:16
【问题描述】:

我在执行数据清理过程时有一个包含 5 列的数据框,我遇到了由文本文件中的回车引起的问题,如 下面的 exp .

输入:

001|Baker St.
London|3|4|7
002|Penny Lane
Liverpool|88|5|7

输出:

001|Baker St. London|3|4|7
002|Penny Lane Liverpool|88|5|7

欢迎提出任何建议。

【问题讨论】:

  • 回车由\r 表示,而换行符为\n,因此将所有\r 替换为空应该可以工作。
  • 请将文字图片替换为实际文字,以便我们复制使用。还要使用您的编码尝试编辑您的问题,因为 cmets 的格式不正确。
  • 嘿,马克,好的,谢谢

标签: python pandas csv file


【解决方案1】:

您可以像这样替换\r

with open("your.csv", "r") as myfile:
 data = myfile.read().replace('\r', '')

示例:

from io import StringIO

# second entry contains a carriage return \r
s = """91|AAA|2010|3
92|BB\rB|2011|4 
93|CCC|2012|5
"""

# StringIO simulates a loaded csv file:

# carriage return still there
StringIO(s).read()
# '91|AAA|2010|3\n92|BB\rB|2011|4\n93|CCC|2012|5\n'

# carriage return gone
StringIO(s).read().replace('\r', '')
# '91|AAA|2010|3\n92|BBB|2011|4\n93|CCC|2012|5\n'

使用熊猫:

data = StringIO(StringIO(s).read().replace('\r', ''))
pd.read_csv(data, sep='|')

Out[35]: 
   91  AAA  2010  3
0  92  BBB  2011  4
1  93  CCC  2012  5

【讨论】:

  • 感谢您的回答,但我只想修复特定行的回车。(以黄色突出显示)
【解决方案2】:

字符串对象提供的内置strip() 方法可以做到这一点;您可以在遍历一行时这样调用它:

cleaned_up_line = line.strip()

正如Python str.strip() docs 告诉我们的那样,它还去掉了空格、换行符和其他特殊字符——在字符串的开头和结尾。

例如:

In [7]: with open('file', 'r') as f: 
   ...:     a = f.readlines() 
   ...:     print(a) 
   ...:                                                                                              
['the\n', 'file\n\r', 'is\n\r', 'here\n', '\n']

In [8]: with open('file', 'r') as f: 
   ...:     a = [line.strip() for line in f.readlines()] 
   ...:     print(a) 
   ...:                                                                                              
['the', 'file', 'is', 'here', '']

【讨论】:

    【解决方案3】:

    您可以将其与正则表达式匹配并将其删除,即re.sub('[\r\n]', '', inputline)

    【讨论】:

      猜你喜欢
      • 2013-07-13
      • 1970-01-01
      • 2014-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-03
      • 2021-01-23
      相关资源
      最近更新 更多