繁体   English   中英

如何排除 8 个字符以下的单词?

[英]How do i exclude words under 8 characters length?

我正在编写一个读取行(字典的单词)的程序,我想排除不包含的单词,例如,最少 8 个字符。

我试图在谷歌上搜索,但我没有找到。

这是我想做的那种程序:

with open('words.txt', 'r') as f: 
    lines = f.read().split('\n')   
    lenght = 8
    #and now the part i struggle with
     If lenght under 8:
        exclude it
    else:
        print(goodword)
    

您可以使用len(line)来查找字符串的长度。

with open('words.txt', 'r') as f: 
    lines = f.read().split('\n')   
length = 8
goodwords = [w for w in lines if len(w) >= length]

print(*goodwords, sep='\n')

goodwords = [...是一个列表goodwords = [... ,可以用标准for loop替换:

goodwords = [] # initiate your list
for word in lines: # evaluate each word
    if len(word) >= length: # word is accepted
        goodwords.append(word)
    # else:
        # no need for an else clause
        # in the event that word has less than 8 letters
        # the code will just continue with the next word

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM