【发布时间】:2014-09-24 04:00:36
【问题描述】:
OS: CentOS 6.5
Python version: 2.7.5
我有一个包含以下信息示例的文件。 我想搜索并替换美分符号并替换为 $0。前面。
Alpha $1.00
Beta ¢55 <<<< note
Charlie $2.00
Delta ¢23 <<<< note
我希望它看起来像这样:
Alpha $1.00
Beta $0.55 <<<< note
Charlie $2.00
Delta $0.23 <<<< note
所以命令行中的这段代码(有效)是:
sed 's/¢/$0./g' *file name*
但是用python写代码不行:
import subprocess
hello = subprocess.call('cat datafile ' + '| sed "s/¢/$0./g"',shell=True)
print hello
每当我尝试粘贴 ¢ 符号时似乎出现错误。
稍微靠近一点,当我在 Python 中打印分号的 unicode 时,它会出现在下面:
print(u"\u00A2")
¢
当我 cat 我的数据文件时,它实际上显示为 ¢ 符号,缺少 Â。
我认为当我尝试使用 Unicode 进行 sed 时,¢ 之前添加的符号不允许我进行搜索和替换。
尝试 unicode 时的错误代码:
hello = subprocess.call(u"cat datafile | sed 's/\uxA2/$0./g'",shell=True)
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 25-26: truncated \uXXXX escape
将 uxA2 固定到 u00A2,我明白了:
sed: -e expression #1, char 7: unknown option to `s'
1
有什么想法/想法吗?
这两个例子我都得到以下错误:
[root@centOS user]# python test2.py
Traceback (most recent call last):
File "test2.py", line 3, in <module>
data = data.decode('utf-8') # decode immediately to Unicode
File "/usr/local/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa2 in position 6: invalid start byte
[root@centOS user]# python test1.py
Traceback (most recent call last):
File "test1.py", line 11, in <module>
hello_unicode = hello_utf8.decode('utf-8')
File "/usr/local/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa2 in position 6: invalid start byte
这是文件的猫:
[root@centOS user]# cat datafile
alpha ¢79
这是数据文件的 Nano:
alpha �79
这是数据文件的 Vim:
[root@centOS user]# vim fbasdf
alpha ¢79
~
再次感谢大家的帮助
回答!!
Rob 和 Thomas 的 SED 输出有效。 文件格式保存为 charset=iso-8859-1。我无法在文档中搜索 utf-8 格式字符。
识别的文件字符集:
file -bi datafile
text/plain; charset=iso-8859-1
使用以下代码更改文件:
iconv -f iso-8859-1 -t utf8 datafile > datafile1
【问题讨论】:
-
感谢@thomas 的 Unicode
-
如果您能向我们展示您遇到的错误,那就太好了。
-
如果这个问题解决了,不要在标题中加上 SOLVED ——这不是 Bugzilla。相反,选择最有效的答案,然后单击它旁边的复选标记大纲将其设置为答案。如果两个答案都不起作用,请添加您自己的答案作为答案并改为选中它。
标签: python python-2.7 sed centos6