python - 使用 Python 从字符串中删除度数符号

标签 python string python-2.7 unicode character-encoding

我正在使用 Python 逐行读取数据的文本文件。其中一行包含度数符号。我想改变这部分字符串。我的脚本使用 line = line.replace("TEMP [°C]", "TempC")。我的代码停在这一行,但根本没有改变字符串,也没有抛出错误。显然,我的替换有一些问题,以至于脚本看不到我的字符串中存在的“TEMP [°C]”。

为了在我的脚本中插入度数符号,我必须在我的 IDE 文件设置中将编码更改为 UTF-8。我在脚本的顶部包含了以下文本。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

如何用“TempC”替换“TEMP [°C]”?

我正在使用 Windows 7 和 Python 2.7 以及 Komodo IDE 5.2

我已经尝试在 Komodo 的 Python Shell 中运行建议的代码,这改变了文件。

# -*- coding: utf-8 -*-
line = "hello TEMP [°C]"
line = line.replace("TEMP [°C]", "TempC")
print(line)
hello TempC

Komodo 的 Python Shell 中的建议代码返回了这个。

line = "TEMP [°C]"
line = line.replace(u"TEMP [°C]", "TempC")
Traceback (most recent call last):
File "<console>", line 0, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in position 6: ordinal not in range(128)

虽然在阅读我的文本文件时,这些建议都不起作用。

最佳答案

根据您的症状,您的 Python str 文字最终会作为它们的 utf-8 编码,因此当您键入时:

"TEMP [°C]"

你实际上得到:

'TEMP [\xc2\xb0C]'

您的文件是一些其他编码(例如 latin-1cp1252),并且由于您是通过纯 open 读取它,您将返回未解码的 str。但是在latin-1cp1252编码中,str'TEMP [\xb0C]'(注意缺少\xc2), 所以 str 比较不认为两个字符串是等价的。

最好的解决办法是用 io.open 替换你对 open 的使用,它使用 Python 3 版本的 open 可以无缝地使用给定的编码进行解码以生成规范的 unicode 表示,类似地,在(对 Python 来说)未知编码中使用 unicode 文字而不是 str,所以在表示度数符号的正确方式上没有分歧(在 unicode 中,只有一种表示方式):

import io

with io.open('myfile.txt', encoding='cp1252') as f:
    for line in f:
        line = line.replace(u"TEMP [°C]", u"TempC")

正如您在编辑中所描述的,您的文件可能是 cp1252(您的编辑说它是 ANSI,which is just a dumb way to describe cp1252),因此选择了编码

注意:如果您打算在整个程序中始终如一地使用 unicode(如果您处理非 ASCII 数据,这是一个不错的主意),您可以将其设为默认值:

from __future__ import unicode_literals
# All string literals are unicode literals unless prefixed with b, as on Python 2

from io import open  # open is now Python 3's open

# No need to qualify with `io.` for `open`, nor put `u` in front of Unicode text
with open('myfile.txt', encoding='cp1252') as f:
    for line in f:
        line = line.replace("TEMP [°C]", "TempC")

真的,你应该转移到 Python 3,其中整个“unicodestr 尝试一起工作但经常失败”的事情通过完全拆分这两种类型来解决.

关于python - 使用 Python 从字符串中删除度数符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54936075/

相关文章:

Python 仅当包含在括号中时才按字符拆分

python - 从二进制数据获取文件类型/扩展名

python - 我怎样才能改变我的Python代码,以便它可以更有效地将txt文件转换为CSV?

c - bsearch() - 在结构数组中查找字符串

python - 如何让多处理稍等一下?

c - 奇怪的错误 : Abort trap while handling character array in C

excel - 文本/字符串上的 DAX LOOKUPVALUE

python - 类型错误 : object cannot be converted to an IntegerDtype

如果时间是列表中的最后一个,Python查找明天的日期

python - tensorflow 中的求和池