我有一个文本文件,我读取文件,经过一些操作后,我把这些行放到另一个文件中。但输入文件有一些土耳其字符,如“İ,Ö,Ü,Ş,Ç,Ğ”。我希望将这些字符转换为英文字符,因为当我以UTF-8编码打开文件时,这些字符不会显示。我的代码如下:
for i in range (len(singleLine)):
if singleLine[i] == "İ":
singleLine.replace(singleLine[i:i+1],"I")
if singleLine[i] == "Ü":
singleLine.replace(singleLine[i:i + 1], "U")
if singleLine[i] == "Ö":
singleLine.replace(singleLine[i:i + 1], "O")
if singleLine[i] == "Ç":
singleLine.replace(singleLine[i:i + 1], "C")
if singleLine[i] == "Ş":
singleLine.replace(singleLine[i:i + 1], "S")
if singleLine[i] == "Ğ":
singleLine.replace(singleLine[i:i + 1], "G")
return singleLine
但是代码在输入文件中无法识别这些土耳其字符,并且在没有任何操作的情况下将它们放入outputfile中。
识别这些字符的方法是什么?基于ASCII码的搜索有什么特殊的方式吗?
答案 0 :(得分:1)
str
个实例是不可变的,因此str.replace()
不会就地运行,而是返回结果。
但是don't do things the hard way。
>>> import unidecode
>>> unidecode.unidecode('İ,Ö,Ü,Ş,Ç,Ğ')
'I,O,U,S,C,G'
答案 1 :(得分:0)
与评论中一样:answer for switch case
我将该方法用作:
choices = {"İ":"I", "ş" : "s"...}
singleLine = singleLine.replace(singleLine[i:i+1],choices.get(singleLine[i],singleLine[i]))
它已经解决了。