简体   繁体   English

如何从txt文件中搜索单词到python

[英]How to search words from txt file to python

How can I show words which length are 20 in a text file? 如何在文本文件中显示长度为20的单词?

To show how to list all the word, I know I can use the following code: 为了说明如何列出所有单词,我知道我可以使用以下代码:

#Program for searching words is in 20 words length in words.txt file
def main():
    file = open("words.txt","r")
    lines = file.readlines()
    file.close()
    for line in lines:
        print (line)
    return

main()

But I not sure how to focus and show all the words with 20 letters. 但我不知道如何聚焦并显示20个字母的所有单词。

Big thanks 太谢谢了

If your lines have lines of text and not just a single word per line, you would first have to split them, which returns a list of the words: 如果你的行有文本行而不是每行一个单词,你首先必须拆分它们,这将返回一个单词列表:

words = line.split(' ')

Then you can iterate over each word in this list and check whether its length is 20. 然后,您可以迭代此列表中的每个单词,并检查其长度是否为20。

for word in words:
    if len(word) == 20:
        # Do what you want to do here

If each line has a single word, you can just operate on line directly and skip the for loop. 如果每一行都有一个单词,您可以直接line操作并跳过for循环。 You may need to strip the trailing end-of-line character though, word = line.strip('\\n') . 您可能需要删除尾部行尾字符, word = line.strip('\\n') If you just want to collect them all, you can do this: 如果你只是想收集它们,你可以这样做:

words_longer_than_20 = []    
for word in words:
        if len(word) > 20:
            words_longer_than_20.append(word)

If your file has one word only per line, and you want only the words with 20 letters you can simply use: 如果您的文件每行只有一个单词,而您只想要包含20个字母的单词,则只需使用:

     with open("words.txt", "r") as f:
         words = f.read().splitlines()
         found = [x for x in words if len(x) == 20]

you can then print the list or print each word seperately 然后,您可以打印列表或单独打印每个单词

You can try this: 你可以试试这个:

f = open('file.txt')
new_file = f.read().splitlines()

words = [i for i in f if len(i) == 20]

f.close()

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

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