获取m到n个字符之间的单词

2024-05-23 14:00:53 发布

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

我试图得到所有以大写字母开头,以句号结尾的名字,在同一行中,字符数在3到5之间

我的文字如下:

 King. Great happinesse

 Rosse. That now Sweno, the Norwayes King,
Craues composition:
Nor would we deigne him buriall of his men,
Till he disbursed, at Saint Colmes ynch,
Ten thousand Dollars, to our generall vse

 King. No more that Thane of Cawdor shall deceiue
Our Bosome interest: Goe pronounce his present death,
And with his former Title greet Macbeth

 Rosse. Ile see it done

 King. What he hath lost, Noble Macbeth hath wonne.

我正在这个link上测试它。我想把3到5之间的单词都取出来,但没有成功。你知道吗


Tags: of结尾大写字母名字字符he文字great
2条回答

这会产生你想要的结果吗?你知道吗

import re

re.findall(r'[A-Z].{2,4}\.', text)

text包含问题中的文本时,它将生成以下输出:

['King.', 'Rosse.', 'King.', 'Rosse.', 'King.']

正则表达式模式匹配首字母大写字母后的任何字符序列。如果需要的话,您可以将其收紧,例如在模式中使用[a-z][A-Z][a-z]{2,4}\.将匹配一个大写字符,后跟2到4个小写字符,后跟一个文字点/句点。你知道吗

如果不需要重复项,可以使用集合来消除它们:

>>> set(re.findall(r'[A-Z].{2,4}\.', text))
set(['Rosse.', 'King.'])

您可能有自己的理由想在这里使用regex,但是Python提供了一组丰富的字符串方法(IMO),使用这些方法更容易理解代码:

matched_words = []
for line in open('text.txt'):
    words = line.split()
    for word in words:
        if word[0].isupper() and word[-1] == '.' and 3 <= len(word)-1 <=5:
            matched_words.append(word)
print matched_words

相关问题 更多 >