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,因为我无法使问题的第一部分起作用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值