gpt4 book ai didi

Python 字符串长度查找字符

转载 作者:可可西里 更新时间:2023-11-01 16:55:53 25 4
gpt4 key购买 nike

我正在尝试使用 python 使用 mapper/reduce 从文本文件中读取输入,并使用 AWS EMR Hadoop(mapper)输出到许多集群中。我想根据他们拥有的字符数输出单词。基本上在下面的 4 行 if 语句中,我要输出 4 种单词。

1.超长单词包含10+个字符。

2.长字包含7、8或9个字符。

3.中字包含4、5或6个字符。

4 短词包含 3、2 或 1 个字符。

不过,这段代码似乎无法正常工作,有人可以帮我解决这个问题吗?如果有帮助,'lword' 就是这个词。谢谢!

   if pattern.match(lword) and (len(lword) <= 10:
print '%s%s%d' % (lword, "\t", 1)

if pattern.match(lword) and (len(lword) >= 7 || len(lword)<=9 :
print '%s%s%d' % (lword, "\t", 1)

if pattern.match(lword) and (len(lword) >= 4 || len(lword)<=6 :
print '%s%s%d' % (lword, "\t", 1)

if pattern.match(lword) and (len(lword) >= 1 || len(lword)<=3 :
print '%s%s%d' % (lword, "\t", 1)

最佳答案

Craig Burgler 已经指出您的代码使用了无效的 || 语法,并展示了如何避免测试 pattern.match(lword) 的次数超出您的需要到。

您可以进行的另一项改进是利用 Python 中的比较可以链接的事实,例如

x = 5
if 4 <= x <= 6:
# True

此外,由于您将不止一次地测试 len(lword),因此将它存储在一个变量中而不是一遍又一遍地计算它是有意义的:

word_length = len(lword)

最后,由于看起来您正在对 lword 执行类似的操作,无论其长度如何,因此您在完成测试后执行该操作。您的最终代码可能如下所示:

if pattern.match(lword):
word_length = len(lword)
if 1 <= word_length <= 3:
category = 1
elif 4 <= word_length <= 6:
category = 2
elif 7 <= word_length <= 9:
category = 3
elif word_length >= 10:
category = 4
else:
category = 0 # lword is empty
print '%s%s%d' % (lword, "\t", category)

关于Python 字符串长度查找字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30045466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com