Python - 编码字符串 - 瑞典语字母

发布于 2024-12-03 00:31:05 字数 1430 浏览 8 评论 0原文

我在使用 Python 的 raw_input 命令(Python2.6)时遇到了一些问题, 由于某种原因, raw_input 没有获得 swedify() 生成的转换后的字符串,这给了我一个我知道的编码错误,这就是我首先创建 swedify() 的原因。 这就是我想要做的:

elif cmd in ('help', 'hjälp', 'info'):
    buffert += 'Just nu är programmet relativt begränsat,\nDe funktioner du har att använda är:\n'
    buffert += ' * historik :: skriver ut all din historik\n'
    buffert += ' * ändra <något> :: ändrar något i databasen, följande finns att ändra:\n'
    print swedify(buffert)

这工作得很好,它按照我想要的方式将瑞典字符输出到控制台。 但是当我尝试(在相同的代码中,使用相同的 \x?? 值,打印这篇文章:

core['goalDistance'] = raw_input(swedify('Hur långt i kilometer är ditt mål: '))
core['goalTime'] = raw_input(swedify('Vad är ditt mål i minuter att springa ' +  core['goalDistance'] + 'km på: '))

然后我得到这个:

C:\Users\Anon>python löp.py
Traceback (most recent call last):
  File "l÷p.py", line 92, in <module>
    core['goalDistance'] = raw_input(swedify('Hur långt i kilometer är ditt mål: '))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe5' in position 5: ordinal not in range(128)

现在我用谷歌搜索,找到了一些“解决方案”,但它们都不起作用,有些悲伤的是我必须创建一个在开始时执行 chcp ??? 的批处理脚本,但这不是一个干净的解决方案

IMO

def swedify(inp):
    try:
        return inp.decode('utf-8')
    except:
        return '(!Dec:) ' + str(inp)

。 我尝试过从编码导入 getencoder、getdecoder 等,但没有任何改善。

I'm having some trouble with Python's raw_input command (Python2.6),
For some reason, the raw_input does not get the converted string that swedify() produces and this giving me a encoding error which i'm aware of, that's why i made swedify() to begin with.
Here's what i'm trying to do:

elif cmd in ('help', 'hjälp', 'info'):
    buffert += 'Just nu är programmet relativt begränsat,\nDe funktioner du har att använda är:\n'
    buffert += ' * historik :: skriver ut all din historik\n'
    buffert += ' * ändra <något> :: ändrar något i databasen, följande finns att ändra:\n'
    print swedify(buffert)

This works just fine, it outputs the swedish characters just as i want them to the console.
But when i try to (in the same code, with same \x?? values, print this piece:

core['goalDistance'] = raw_input(swedify('Hur långt i kilometer är ditt mål: '))
core['goalTime'] = raw_input(swedify('Vad är ditt mål i minuter att springa ' +  core['goalDistance'] + 'km på: '))

Then i get this:

C:\Users\Anon>python löp.py
Traceback (most recent call last):
  File "l÷p.py", line 92, in <module>
    core['goalDistance'] = raw_input(swedify('Hur långt i kilometer är ditt mål: '))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe5' in position 5: ordinal not in range(128)

Now i've googled around, found some "solutions" but none of them work, some sad that i have to create a batch script that executes chcp ??? in the beginning, but that's not a clean solution IMO.

Here is swedify:

def swedify(inp):
    try:
        return inp.decode('utf-8')
    except:
        return '(!Dec:) ' + str(inp)

Any solutions on how to get raw_input to read my return value from swedify()?
i've tried from encodings import getencoder, getdecoder and others but nothing for the better.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

糖粟与秋泊 2024-12-10 00:31:05

您提到您收到一个编码错误,这促使您首先编写 swedify,并且您已经找到了围绕 chcp(Windows 命令)的解决方案。

在带有 UTF-8 终端的 *nix 系统上,swedify 不是必需的:

>>> raw_input('Hur långt i kilometer är ditt mål: ')
Hur långt i kilometer är ditt mål: 100
'100'
>>> a = raw_input('Hur långt i kilometer är ditt mål: ')
Hur långt i kilometer är ditt mål: 200
>>> a
'200'

FWIW,当我使用 swedify 时,我得到了与您相同的错误do:

>>> def swedify(inp):
...     try:
...         return inp.decode('utf-8')
...     except:
...         return '(!Dec:) ' + str(inp)
... 
>>> swedify('Hur långt i kilometer är ditt mål: ') 
u'Hur l\xe5ngt i kilometer \xe4r ditt m\xe5l: '
>>> raw_input(swedify('Hur långt i kilometer är ditt mål: '))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe5' in position 5: ordinal not in range(128)

您的 swedify 函数返回一个 unicode 对象。内置的 raw_input 只是对 unicode 对象不满意。

>>> raw_input("å")
åeee
'eee'
>>> raw_input(u"å")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe5' in position 0: ordinal not in range(128)

您可能想在 Python 3 中尝试此操作。请参阅此 Python bug

另外感兴趣的是:如何读取 Unicode 输入和在 Python 中比较 Unicode 字符串?

更新根据这篇博文是一种设置系统默认编码的方法。这可能值得一试。

You mention the fact that you received an encoding error which motivated you to write swedify in the first place, and you have found solutions around chcp which is a Windows command.

On *nix systems with UTF-8 terminals, swedify is not necessary:

>>> raw_input('Hur långt i kilometer är ditt mål: ')
Hur långt i kilometer är ditt mål: 100
'100'
>>> a = raw_input('Hur långt i kilometer är ditt mål: ')
Hur långt i kilometer är ditt mål: 200
>>> a
'200'

FWIW, when I do use swedify, I get the same error you do:

>>> def swedify(inp):
...     try:
...         return inp.decode('utf-8')
...     except:
...         return '(!Dec:) ' + str(inp)
... 
>>> swedify('Hur långt i kilometer är ditt mål: ') 
u'Hur l\xe5ngt i kilometer \xe4r ditt m\xe5l: '
>>> raw_input(swedify('Hur långt i kilometer är ditt mål: '))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe5' in position 5: ordinal not in range(128)

Your swedify function returns a unicode object. The built-in raw_input is just not happy with unicode objects.

>>> raw_input("å")
åeee
'eee'
>>> raw_input(u"å")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe5' in position 0: ordinal not in range(128)

You might want to try this in Python 3. See this Python bug.

Also of interest: How to read Unicode input and compare Unicode strings in Python?.

UPDATE According to this blog post there is a way to set the system's default encoding. This might be worth a try.

白云不回头 2024-12-10 00:31:05

对我来说它工作得很好:

#-*- coding: utf-8 -*-
import sys
import codecs
koden=sys.stdin.encoding

a=raw_input( u'Frågan är öppen? '.encode(koden))
print a

Per

For me it worked fine with:

#-*- coding: utf-8 -*-
import sys
import codecs
koden=sys.stdin.encoding

a=raw_input( u'Frågan är öppen? '.encode(koden))
print a

Per

可爱咩 2024-12-10 00:31:05

在 Windows 上,控制台的本机 Unicode 支持已损坏。即使是明显的 UTF-8 代码页也不是正确的修复方法。

要使用 Windows 控制台读写,您需要使用 https://github.com/Drekin/win-unicode -console,直接与底层控制台API配合使用,从而可以正确读写多字节字符。

On Windows, the console's native Unicode support is broken. Even the apparent UTF-8 codepage isn't a proper fix.

To read and write with Windows console you need use https://github.com/Drekin/win-unicode-console, which works directly with the underlying console API, so that multi-byte characters are read and written correctly.

我最亲爱的 2024-12-10 00:31:05

使用瑞典区域设置时,Windows 命令提示符使用代码页 850 (https://en.wikipedia.org/wiki/ Code_page_850)。
使用它可能是因为与旧的 MS-Dos 程序向后兼容。

您可以通过输入以下命令将 Windows 命令提示符设置为使用 UTF-8 作为编码:
chcp 65001 (Windows 中的 Unicode 字符命令行 - 如何?

Windows command prompt uses Codepage 850 when using Swedish regional settings (https://en.wikipedia.org/wiki/Code_page_850).
It's probably used because of backwards compatibility with old MS-Dos programs.

You can set Windows command prompt to use UTF-8 as encoding by entering:
chcp 65001 (Unicode characters in Windows command line - how?)

黑白记忆 2024-12-10 00:31:05

在脚本的最顶部尝试这个神奇的注释:

# -*- coding: utf-8 -*-

以下是有关它的一些信息:
http://www.python.org/dev/peps/pep-0263/

Try this magic comment at the very top of your script:

# -*- coding: utf-8 -*-

Here is some information about it:
http://www.python.org/dev/peps/pep-0263/

十年九夏 2024-12-10 00:31:05

解决很多问题:

编辑:C:\Python??\Lib\Site.py
将“del sys.setdefaultencoding”替换为“pass”

那么,
将其放在代码的顶部:

sys.setdefaultencoding('latin-1')

修复瑞典语/非 UTF8 兼容字符的圣杯。

Solution to a lot of problems:

Edit: C:\Python??\Lib\Site.py
Replace "del sys.setdefaultencoding" with "pass"

Then,
Put this in the top of your code:

sys.setdefaultencoding('latin-1')

The holy grail of fixing the Swedish/non-UTF8 compatible characters.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文