Python 如何在文本文件中找到最长的单词
在本文中,我们将向您展示如何使用python从给定的文本文件中打印出所有最长的单词。最长的单词是与文本文件中最长单词(最大长度)长度相同的单词。
假设我们已经拿到一个名为ExampleTextFile.txt 的文本文件,其中包含一些随机文本。我们将返回给定文本文件中的所有最长的单词。
ExampleTextFile.txt
Good Morning Tutorials Point
This is Tutorials Point sample File
Consisting of Specific
abbreviated
source codes in Python Seaborn Scala
Imagination
Summary and Explanation
Welcome user
Learn with a joy
步骤
以下是执行所需任务的算法/步骤:
- 创建一个变量来存储文本文件的路径。
-
使用 open() 函数(打开一个文件并返回一个文件对象作为结果)通过传递文件名和模式作为参数来以只读模式打开文本文件(这里的“r”表示只读模式)。
with open(inputFile, 'r') as filedata:
-
使用 read() 函数创建一个变量来读取文本文件数据(从文件中读取指定字节数并将它们返回。默认值为-1,表示整个文件),并使用 split() 函数将其拆分为给定文本文件的单词列表(将字符串按照分隔符拆分成列表。我们可以定义分隔符;默认的分隔符是任何空白字符)。
-
使用 len() 函数(返回对象中的项数。当对象是字符串时,它返回字符串的字符数)和 max() 函数(返回最高值的项,或返回可迭代对象中最高值的项)从上述单词列表中找到最长单词的长度。
len(max(words List, key=len))
-
key=len 指定我们必须根据单词的长度获取单词,我们将使用max()函数获取长度最长的单词,并使用len()函数获取长度最长的单词的长度。
-
使用 列表推导 ,获取所有最长长度的单词,并将它们保存在另一个变量中。在这里,我们遍历文件中的每个单词,并使用列表推导中的for循环检查该单词的长度是否等于最长单词的长度。
list comprehension:
-
当您希望基于现有列表的值构建一个新列表时,列表推导提供了一种更短/简洁的语法。
-
从给定的文本文件中打印出所有最长的单词。
-
使用 close() 函数(用于关闭已打开的文件)关闭输入文件。
示例
以下程序检查最长单词的长度,并打印与最长单词长度相同的所有单词,从给定的文本文件中获取
# input text file
inputFile = "ExampleTextFile.txt"
# Opening the given file in read-only mode.
with open(inputFile, 'r') as filedata:
# Getting the list of words of a file
wordsList = filedata.read().split()
# finding the length of the longest word in the above words list
longestWordLength = len(max(wordsList, key=len))
# Storing all the words having the maximum length(longest word length)
# Here, we are checking all the words whose length is equal to that of the longest word
result = [textword for textword in wordsList if len(textword) == longestWordLength]
# Print the longest words from a text file
print("The following are the longest words from a text file:")
print(result)
# Closing the input file
filedata.close()
输出
执行上述程序后将生成以下输出:
The following are the longest words from a text file:
['abbreviated', 'Imagination', 'Explanation']
在这个程序中,我们从一个文本文件中读取了一些随机文本。我们读取整个文件并将其分解为单词。我们在获得单词后确定了最长单词的长度。然后我们逐个单词地检查文件,检查相应单词的长度是否等于最短单词的长度。如果是真的,我们将打印这些单词并关闭打开的文件。
结论
因此,从本文中我们学到了如何一次读取整个文件内容,这对于在整个文档中搜索任何单词而不是逐行搜索非常有用。我们还学会了如何使用split()函数将文件内容分割成单词,并确定最短单词的长度。确定最大长度后,我们学会了如何扫描整个文件内容以查找最长单词。