Python 查找字符的字符串长度

Python String length to find character

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

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

2.Long 单词包含 7、8 或 9 个字符。

3.Medium 单词包含 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)

您想使用 and 而不是 '| |'在最后三个字长测试中。例如,一个更具可读性的测试是 len(lword) in [7. 8. 9]

另外第一个字长测试应该是>= 10而不是<= 10

因此,假设 print 语句是根据 lword 大小的不同操作的占位符:

if pattern.match(lword):
   if len(lword) >= 10:
       print '%s%s%d' % (lword, "\t", 1)
   elif len(lword) in [7, 8, 9] :
       print '%s%s%d' % (lword, "\t", 1)
   elif len(lword) in [4, 5, 6] :
       print '%s%s%d' % (lword, "\t", 1)
   else: # lword is between one and three characters long
       print '%s%s%d' % (lword, "\t", 1)

看看这个:

if (len(lword)) >= 10:
        print '%s%s%d' % (lword, "\t", 1)

elif (len(lword) >= 7) and (len(lword) <= 9) :
        print '%s%s%d' % (lword, "\t", 1)

elif (len(lword) >= 4) and (len(lword) <= 6) :
        print '%s%s%d' % (lword, "\t", 1)

elif (len(lword) >= 1) and (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)