Python文本文件,打印以“the”开头的所有单词的列表

2024-05-14 22:35:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须编写一个代码,列出所有以“the”开头的单词(例如,在那里,那么,the)。但列表中没有任何重复项。有人能帮忙吗?到目前为止,我所拥有的一切。在

def getbook():
    bookname = input("What is the name of the text file?")
    bookFile = open(bookname, 'r')
    bookString = bookFile.read()
    lowerBook = bookString.lower()
    wordList = lowerBook.split()
    return wordList

import string

def listAllThe(longString):
    theList = []
    for i in longString:
        if i == 'the':
            theList.append( i)
    return theList

def final():
    book = getbook()
    getList = listAllThe(book)
    print (getList)

final()

Tags: thereturndeffinalgetbookwordlistbookthelist
2条回答

您应该签出^{}数据类型,它不允许重复,并且在其中搜索是O(1)(恒定时间)。在

另外,您应该签出^{}函数,如果字符串以作为参数传入的值开始,它将返回true。在

然后在listAllThe函数中,可以使用函数set()将{}初始化为set,然后进行if条件检查,如-i.startswith('the')。在

更改后的代码看起来像-

def getbook():
    bookname = input("What is the name of the text file?")
    bookFile = open(bookname, 'r')
    bookString = bookFile.read()
    lowerBook = bookString.lower()
    wordList = lowerBook.split()
    return wordList

import string

def listAllThe(longString):
    theList = set()
    for i in longString:
        if i.startswith('the'):
            theList.add(i)
    return theList

def final():
    book = getbook()
    getList = listAllThe(book)
    print (getList)

final()

这是一种使用Python列表理解可以轻松完成的事情。生成的列表可用于初始化set,这将删除重复项:

set([x for x in bookFile.read().lower().split() if x.startswith('the')])

相关问题 更多 >

    热门问题