1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python找到长度最长的单词长度 python中的正则表达式:查找长度为n或更长的单词...

python找到长度最长的单词长度 python中的正则表达式:查找长度为n或更长的单词...

时间:2024-01-20 20:17:49

相关推荐

python找到长度最长的单词长度 python中的正则表达式:查找长度为n或更长的单词...

我们刚刚学习了在我的第一门Python课程中使用正则表达式(对编程非常陌生),我正在努力解决的一个家庭作业问题要求我们使用正则表达式查找长度为n或更长的所有单词,然后使用该正则表达式查找从文本文件中使用的格式词。

当我想测试一个特定的长度时,我没有问题,但是当我使用一个任意变量n时,它返回一个空列表:

import re

with open('shakespeare.txt') as file:

shakespeare = file.read()

n = 10 #if I take this out and put an actual number in the curly bracket below, it works just fine.

words = re.findall('^[A-Za-z\'\-]{n,}', shakespeare, re.M)

print(words)

len(words)

我不知道我做错了什么以及如何解决这个问题。非常感谢您的帮助!

有关更多上下文…

为了找到最长的单词,我使用了:

#for word with special characters such as '-' and '''

longest_word = max(re.findall('\S+', shakespeare, re.M), key = len)

#for word without special characters:

longest_pure_word = max(re.findall('[A-Za-z]+ ', shakespeare, re.M), key = len)

output1(special char): tragical-comical-historical-pastoral

output2(pure word): honorificabilitudinitatibus

我没有使用N,因为我无法使问题的第一部分起作用。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。