包含apostroph时,Python会计算字符串错误的大写字母

时间:2016-03-06 18:20:32

标签: python string

大家好我编写了以下代码,但每当输入文本包含一个叛逆者('

时我都会收到错误
from collections import Counter
import string


def count_letters(word):
    BAD_LETTERS = "a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z,  "
    return len([letter for letter in word if letter not in BAD_LETTERS])
    for letters in set(words):
            return count[letters]

word = "The Catcher in the Rye by J.D. Salinger TO MY MOTHER If you really want to hear about it, the first thing you’ll probably want to know is where I was born, an what my lousy childhood was like, and how my parents were occupied and all before they had me, and all that David Copperfield kind of crap, but I don’t feel like going into it, if you want to know the truth. In the first place, that stuff bores me, and in the second place, my parents would have about two hemorrhages apiece if I told anything pretty personal about them. They’re quite touchy about anything like that, especially my father. They’re nice and all, I’m not saying that, but they’re also touchy as hell. "
print count_letters(word)

我收到以下错误:

% python /Users/shirin/Desktop/capitalsnew.py      [355]
  File "/Users/shirin/Desktop/capitalsnew.py", line 11
SyntaxError: Non-ASCII character '\xe2' in file /Users/shirin/Desktop/capitalsnew.py on line 11, but no encoding declared

有关详细信息,请参阅http://python.org/dev/peps/pep-0263/ 任何想法,提前谢谢!

2 个答案:

答案 0 :(得分:0)

选项1:

此字符未在ASCII中定义,而不是使用此字符'

我替换了字符并且没​​有错误:

word = "The Catcher in the Rye by J.D. Salinger TO MY MOTHER If you really want to hear about it, the first thing you'll probably want to know is where I was born, an what my lousy childhood was like, and how my parents were occupied and all before they had me, and all that David Copperfield kind of crap, but I dont feel like going into it, if you want to know the truth. In the first place, that stuff bores me, and in the second place, my parents would have about two hemorrhages apiece if I told anything pretty personal about them. They're quite touchy about anything like that, especially my father. They're nice and all, I'm not saying that, but they're also touchy as hell. "

选项2:

更改Python源代码编码:https://www.python.org/dev/peps/pep-0263/

示例:

      #!/usr/bin/python
      # -*- coding: latin-1 -*-
      import os, sys
      ...

      #!/usr/bin/python
      # -*- coding: iso-8859-15 -*-
      import os, sys
      ...

      #!/usr/bin/python
      # -*- coding: ascii -*-
      import os, sys
      ...

答案 1 :(得分:0)

您需要声明文件编码才能使用非ASCII字符,例如'''。我认为latin-1是python 2的推荐编码,所以把它放在文件的最开头(但是如果你有一个shebang之后):

# -*- coding: latin-1 -*-