如何利用Python查找文件中最长的行/字符串

228 阅读1分钟

编码挑战

💬 挑战:如何用Python查找文件中最长的行或字符串?

给出下面这个文本文件。

根据你要找的具体内容,你想找到文件中最长的字符串单词**(A**)或最长的行**(B**)。

without
python
we'd all have to
write 
java
code

接下来让我们深入了解这两种变体。

方法1:使用Python查找文本文件中最长的行

要用Python找到一个文本文件中最长的一行,用 [open()](https://blog.finxter.com/python-open-function/)函数打开文件,并使用file.readlines() 函数读取文件内容的行数列表。然后用 [max(lines, key=len)](https://blog.finxter.com/python-max/)函数,使用length函数作为键来查找最长的一行。

下面是代码。

with open('my_file.txt', mode='r') as f:
    lines = f.readlines()
    longest_line = max(lines, key=len)
    print('The longest line is:', longest_line)

输出结果是。

The longest line is: we'd all have to

方法2:使用Python查找文本文件中最长的字符串单词

找到文本文件中最长字符串的一个简单而直接的方法是打开文件,用file.readlines() ,在所有的行上循环,把每一行分成一个字的列表,用 [string.split()](https://blog.finxter.com/python-string-split/)循环这个单词列表,并在一个变量中记录最长的单词。

这是找到文本文件中最长单词的Python代码段。

with open('my_file.txt', 'r') as f:
    longest_word = ''
    for line in f.readlines():
        for word in line.split():
            if len(word)>len(longest_word):
                longest_word = word
    print('The longest word in the file is:', longest_word)

这里是正确的输出,即文本中最长的单词。

The longest word in the file is: without

注意,你也可以用下面的方法来单行化,即结合列表理解[max()](https://blog.finxter.com/python-max/)函数。

longest = max([word for line in open('my_file.txt').readlines() for word in line.split()], key=len)

结果是一样的。

print('The longest word in the file is:', longest)
# The longest word in the file is: without