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

Python 获取m和n个字符之间的单词,python,regex,Python,Regex,我试图得到所有以大写字母开头,以句号结尾的名字,在同一行中,字符数在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

我试图得到所有以大写字母开头,以句号结尾的名字,在同一行中,字符数在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.

我正在测试这个。我正在尝试获取3到5之间的所有单词,但没有成功。

这会产生您想要的输出吗

import re

re.findall(r'[A-Z].{2,4}\.', text)
text
包含问题中的文本时,它将生成以下输出:

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

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

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

这会产生你想要的输出吗

import re

re.findall(r'[A-Z].{2,4}\.', text)
text
包含问题中的文本时,它将生成以下输出:

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

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

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

在这里使用regexs可能有自己的原因,但是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
匹配的单词=[]
对于打开的行('text.txt'):
words=line.split()
用文字表示:

如果word[0].isupper()和word[-1]='.'以及3您可能有自己的理由想在这里使用正则表达式,但是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
匹配的单词=[]
对于打开的行('text.txt'):
words=line.split()
用文字表示:

如果单词[0].isupper()和单词[-1]='.'和3,请将所有复制数据发布在问题正文中。到底什么对你不起作用?我不知道你所说的回购数据是什么意思。我没有找到匹配项,如果你问的是
I{3,5}
regex,必须在问题中提供,这就是规则。而且它不会为您获取任何匹配项,因为它匹配3到5个连续的
I
s。我想你需要
\b[A-Z][A-Z]{3,5}\b(?=\)
没有任何遗漏,但不确定…仅供参考:
r'[A-Z].{2,4}.
也匹配
F12.
。既然你接受了答案,我想这是意料之中的。请将所有的复制数据发布在这里,在问题正文中。到底什么对你不起作用?我不知道你所说的回购数据是什么意思。我没有找到匹配项,如果你问的是
I{3,5}
regex,必须在问题中提供,这就是规则。而且它不会为您获取任何匹配项,因为它匹配3到5个连续的
I
s。我想你需要
\b[A-Z][A-Z]{3,5}\b(?=\)
没有任何遗漏,但不确定…仅供参考:
r'[A-Z].{2,4}.
也匹配
F12.
。既然你接受了答案,我想这是意料之中的。谢谢。但我也得到了“wonne”,在results@DhirajEadara禁用忽略案例button@DhirajEadara:是的,正如E先生所说,禁用Pythex中的
忽略案例
按钮。谢谢。但我也得到了“wonne”,在results@DhirajEadara禁用忽略案例button@DhirajEadara:是的,正如E先生所说,禁用Pythex中的
IGNORECASE
按钮。