在Python中从.txt文件读取特殊字符

8
这段代码的目的是查找书中单词使用的频率。
我试图读入一本书的文本,但以下行会使我的代码出错: precious protégés。不,先生们;他总是给他们展示一对干净的鞋子,特别是é字符。
我已经查看了以下文档,但我还不太理解它:https://docs.python.org/3.4/howto/unicode.html 以下是我的代码:
import string
# Create word dictionary from the comprehensive word list 
word_dict = {}
def create_word_dict ():

  # open words.txt and populate dictionary
  word_file = open ("./words.txt", "r")
  for line in word_file:
    line = line.strip()
    word_dict[line] = 1

# Removes punctuation marks from a string
def parseString (st):
  st = st.encode("ascii", "replace")
  new_line = ""
  st = st.strip()
  for ch in st:
    ch = str(ch)
    if (n for n in (1,2,3,4,5,6,7,8,9,0)) in ch or ' ' in ch or ch.isspace() or ch == u'\xe9':

      print (ch)
      new_line += ch
    else:
      new_line += ""
  # now remove all instances of 's or ' at end of line
  new_line = new_line.strip()
  print (new_line)
  if (new_line[-1] == "'"):
    new_line = new_line[:-1]
  new_line.replace("'s", "")
  # Conversion from ASCII codes back to useable text
  message = new_line
  decodedMessage = ""
  for item in message.split():
    decodedMessage += chr(int(item))
  print (decodedMessage)
  return new_line

# Returns a dictionary of words and their frequencies
def getWordFreq (file):

  # Open file for reading the book.txt
  book = open (file, "r")

  # create an empty set for all Capitalized words
  cap_words = set()

  # create a dictionary for words
  book_dict = {}
  total_words = 0

  # remove all punctuation marks other than '[not s]
  for line in book:
    line = line.strip()
    if (len(line) > 0):
      line = parseString (line)

    word_list = line.split()

    # add words to the book dictionary
    for word in word_list:
      total_words += 1
      if (word in book_dict):
        book_dict[word] = book_dict[word] + 1
      else:
        book_dict[word] = 1
  print (book_dict)

  # close the file
  book.close()

def main():
  wordFreq1 = getWordFreq ("./Tale.txt")
  print (wordFreq1)

main()

我收到的错误信息如下:
Traceback (most recent call last):
  File "Books.py", line 80, in <module>
    main()
  File "Books.py", line 77, in main
    wordFreq1 = getWordFreq ("./Tale.txt")
  File "Books.py", line 60, in getWordFreq
    line = parseString (line)
  File "Books.py", line 36, in parseString
    decodedMessage += chr(int(item))
OverflowError: Python int too large to convert to C long                      

2
你可能已经检查过了,否则请检查所接收数据的编码。它是UTF-8、ISO-8859-1、WIN-1252还是UCS-2呢?没什么比期望是UTF-8却遇到一个高位设置了但不是UTF-8而是8位字符的情况更让人无语了。 - Matthew V Carey
我无法找到如何在记事本中检查编码的方法?但我也使用iPython。我该怎么找出来呢? - Daniel Schulze
在Windows下,NotePad++可以给你提示。在Linux上,“file”命令会告诉你。或者使用十六进制查看器或二进制编辑器来查看段落中的实际字节。 - Matthew V Carey
在记事本中,编码设置为ANSI。 - Daniel Schulze
在去除标点符号时,您是指彻底删除 é 字符还是将其转换为普通的 e - martineau
显示剩余2条评论
3个回答

18

当你在Python中打开文本文件时,默认的编码格式是ANSI,因此它不包含你的é字符。尝试使用

word_file = open ("./words.txt", "r", encoding='utf-8')

默认情况下编码方式是什么,取决于 - mkrieger1
“ANSI默认”?你从哪里得到这个信息的?根据文档所述:“如果未指定encoding,则使用的编码取决于平台”。 - wjandrea

1
我能想到的最好方法是将每个字符读取为ASCII值,存入数组中,然后取char值。例如,97是ASCII码的“a”,如果您使用char(97),它将输出“a”。查看一些在线ASCII表以获取特殊字符的值。

1
任何值得存储的 ASCII 表都不会包含带重音符号的字符。 - Jongware

0

尝试:

def parseString(st):
    st = st.encode("ascii", "replace")

    # rest of code here

你现在遇到的新错误是因为你正在对一个整数(即数字)调用isalpha函数。
试试这个:
for ch in st:
    ch = str(ch)
    if (n for n in (1,2,3,4,5,6,7,8,9,0) if n in ch) or ' ' in ch or ch.isspace() or ch == u'\xe9':

        print (ch)

我得到了以下错误: 文件“Books.py”,第30行 st = st.encode(“ascii”,“replace”) ^ SyntaxError:扫描字符串文字时出现EOL - Daniel Schulze
我更新了代码,导致出现了一个新的错误信息。 - Daniel Schulze
新的错误是因为str.encode()返回的是一个字节对象,而不是一个字符串。 - martineau
那么现在我该如何将这些 ASCII 值转换回单词呢?因为我需要制作一个包含此书中使用的唯一单词的字典。代码现在可以工作,但我得到的是一个由唯一数字集合填充的字典。 - Daniel Schulze
所以我正在尝试将这些ASCII字符转换回文本,但是我收到了一个新的错误消息。 - Daniel Schulze
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接