import operator
import jieba
with open("chinews.txt", "r", encoding = "utf-8") as f:
data = f.read()
print(data,)
special_char = list(,。”、“:!)
Input In [13]
special_char = list(,。”、“:!)
^
SyntaxError: invalid character ',' (U+FF0C)
字符串编码的问题,注意全角和半角字符问题
Python 默认使用的是 ASCII 编码,而中文标点符号不在 ASCII 编码字符集中。
你可以使用 Unicode 编码的方式来替换中文标点符号,参考:
import jieba
with open("chinews.txt", "r", encoding="utf-8") as f:
data = f.read()
print(data)
special_char = ["\uFF0C", "\u3002", "\u201C", "\u201D", "\u3001", "\uFF1A", "\uFF01"]
# 中文标点符号 Unicode 编码
for c in special_char:
data = data.replace(c, " ") # 使用空格替换中文标点符号
words = list(jieba.cut(data))
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
sorted_word_count = sorted(word_count.items(), key=operator.itemgetter(1), reverse=True)
for word, count in sorted_word_count:
print(word, count)
该回答引用GPTᴼᴾᴱᴺᴬᴵ
在 Python 中,如果要使用中文字符,需要在文件开头添加编码声明,例如 # -- coding: utf-8 --。如果不添加编码声明,Python 可能无法正确处理中文字符,导致出现类似 U+FF0C 的错误。
此外,在你的代码中,特殊字符列表中的中文逗号“,”也是一个问题。你可以使用英文逗号来代替,例如:
special_char = [',', '。', '“', '”', '、', ':', '!']
这样应该就不会出现 U+FF0C 错误了。