去掉大写字母中的一些单词,但不要去掉小写字母较小的单词

2024-05-14 16:42:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个很长的文本文件,看起来像这样:

'a_lot(icl>how)', '', 'TO', 'A', 'VERY', 'GREAT', 'DEGREE', 'OR', 'EXTENT', 'WE', 'ENJOYED', 'OURSELVES', 'A', 'LOT', 'beaucoup', '{CAT(CATADV)}', '', 'a_lot(icl>how)', '', 'TO', 'A', 'VERY', 'GREAT', 'DEGREE', 'OR', 'EXTENT', 'WE', 'ENJOYED', 'OURSELVES', 'A', 'LOT', 'cher', '{CAT(CATADV)}'

我想用Python Regex做的是删除所有大写单词作为'TO', 'A', 'VERY', 'GREAT', 'DEGREE', 'OR', 'EXTENT', 'WE', 'ENJOYED', 'OURSELVES', 'A', 'LOT',。你知道吗

我如何用regex实现这一点,同时将单词保持为beaucoupcher(法语较低的单词)和{CAT(CATADV)}?你知道吗

更清楚地说,我希望我的输出是:

 'a_lot(icl>how)', '', 'beaucoup', '{CAT(CATADV)}', '', 'a_lot(icl>how)', 'cher', '{CAT(CATADV)}'

Tags: ortoextentcathowverywelot
2条回答

试试这个

 import enchant
 d = enchant.Dict("en_US")
 list = ['a_lot(icl>how)', '', 'TO', 'A', 'VERY', 'GREAT', 'DEGREE', 'OR', 'EXTENT', 'WE', 'ENJOYED', 'OURSELVES', 'A', 'LOT', 'beaucoup', '{CAT(CATADV)}', '', 'a_lot(icl>how)', '', 'TO', 'A', 'VERY', 'GREAT', 'DEGREE', 'OR', 'EXTENT', 'WE', 'ENJOYED', 'OURSELVES', 'A', 'LOT', 'cher', '{CAT(CATADV)}']

 list_of_words = [word for word in list if not d.check(word)]

现在还不清楚你希望在这里取得什么成就。如果任务是只打印大写的单词,请尝试

for word in words:
    if all(x.isupper() for x in word):
        print(word)

如果你坚持使用正则表达式,试试看

regex = re.compile(r'^[A-Z]+$')
for word in words:
    if regex.match(word):
        print(word)

这将不会打印包含大写和其他非小写符号的单词;如果您需要,可以探索其他有用的谓词,或者简单地尝试not x.islower()而不是x.isupper()。你知道吗

相关问题 更多 >

    热门问题