【Python】英文内容标题化处理

按照语法标准的英文文字标题化的 Python 程序实现。

前言

写一些长标题英文文章的时候,我们常遇到大小写问题:不知哪些词该大写,那些词该小写。今天站长带大家用 Python 边实现边讲解。

正文

标题化(Titleize)是指将一段文字处理为标题的标准格式,要写一篇优秀的英文文章,就必须遵守一定标题单词的大小写规则。

代码

文章实现参考 TabulateJarl8/titleize 的实现。

"""
@File    :   titleize.py
@Time    :   2023/03/15 23:39:26
@Author  :   @灰尘疾客
@Version :   1.0
@Site    :   https://www.gkcoll.xyz
@Desc    :   None
@Licence :   WTFPL ↓↓↓

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
                    Version 2, December 2004

 Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>

 Everyone is permitted to copy and distribute verbatim or modified
 copies of this license document, and changing it is allowed as long
 as the name is changed.

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. You just DO WHAT THE FUCK YOU WANT TO.

"""

# Import the Natural Language Toolkit lib(nltk) and the built-in Regex lib.
# If you didn't install the nltk, install it by `pip install nltk` or `pip3 install nltk`.

import nltk
import string

# Define the two sets of tags that should be capitalized or need special process.
CAPITALIZE_TAGS = set(['NN', 'PRP', 'VB', 'RB', 'JJ', 'WDT', 'WP', 'WRB'])
SPECIAL_SITUATION_TAGS = set(["IN", "UH", "CC", "DT", "TO"])

def titleize(obj: str) -> str:
    """
    核心函数: 标题化传入的内容
    :param obj: 待处理的文字。
    """
    words = nltk.pos_tag(nltk.word_tokenize(obj))
    newwords = []

    for word in words:
        if word[1] in SPECIAL_SITUATION_TAGS and len(word[0]) < 5:
            newwords.append(word[0])
        else:
            newwords.append(word[0].capitalize())

    return " ".join(newwords)

依赖

代码中用到了自然语言工具集(Natual Languages Toolkit)第三方库,使用前需确保已安装(安装命令 pip install nltk),且前几次使用可能会提示下载一些资源,请按要求下载否则无法正常使用。

说明

本代码遵守 WTFPL 开源,二次开发请细读其原文。(手动滑稽)

总结

从代码中我们不难看出:

实词标题化的普遍规律。

还有首词和尾词标题化。

另外,虚词及不定式词字母大于五个需要大写首字母的规则。

测试

从国务院英文站点复制了一段关于 CPC 第二十届全国代表大会的材料标题。

print(titleize("full text of the report to the 20th national congress of the communist party of china"))

结果:

Full Text of the Report to the 20th National Congress of the Communist Party of China

完美!

阅读剩余
THE END