如何从文本中去除撇号?

1 投票
1 回答
1555 浏览
提问于 2025-04-18 14:12

这不是一个重复的问题,我已经在StackOverflow上搜索并尝试了各种答案,但都没有成功。

我正在用Python把一个.docx文件转换成纯文本,但在命令行上打印出来时,字符 " ' " 显示成了奇怪的符号(比如 canΓÇÖt)。下面是我的代码:

if file.endswith('.docx'):
        docx = zipfile.ZipFile(fullpath)
        content = docx.read('word/document.xml')
        cleaned = re.sub('<(.|\n)*?>','',content)
        text=unescape(cleaned)
        newtext = text.replace("'", " ")
        print newtext

在StackOverflow上找到的答案让我尝试了 "text=unescape(cleaned)" 和 "text.replace("'", " ")",但结果还是不理想。

我该如何从字符串变量中去掉撇号?或者更好的是,如何确保撇号能正确显示?

1 个回答

2

我猜你的问题是,你看到的是‘some_text_here’,而不是'some_text_here'。也就是说,你看到的是单个的弯曲引号(或者叫“智能引号”)。

你可以这样做:

if file.endswith('.docx'):
    ...
    cleaned = re.sub('<(.|\n)*?>','',content)
    cleaner = string.translate(cleaned, None, ["‘","’"])
    # python3 has to use:
    # # cleaner = cleaned.translate(str.maketrans({'‘':'','’':''}))

供参考:

>>> ord("‘") # left single smart quote
# 8216
>>> ord("’") # right single smart quote
# 8217
>>> ord("'") # single apostrophe
# 39

撰写回答