python 如何打开文件并找到一行的最长长度然后将其打印出来
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1292630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to open a file and find the longest length of a line and then print it out
提问by BForce01
Here's is what I have done so far but the length function isn't working.
这是我到目前为止所做的,但长度函数不起作用。
import string
def main():
print " This program reads from a file and then prints out the"
print " line with the longest length the line ,or with the highest sum"
print " of ASCII values , or the line with the greatest number of words"
infile = open("30075165.txt","r")
for line in infile:
print line
infile.close()
def length():
maxlength = 0
infile = open("30075165.txt","r")
for line in infile:
linelength = lengthofline
if linelength > maxlength:
#If linelength is greater than maxlength value the new value is linelength
maxlength = linelength
linelength = line
print ,maxlinetext
infile.close()
回答by Steef
For Python 2.5 to 2.7.12
对于 Python 2.5 到 2.7.12
print max(open(your_filename, 'r'), key=len)
For Python 3 and up
对于 Python 3 及更高版本
print(max(open(your_filename, 'r'), key=len))
回答by kjfletch
large_line = ''
large_line_len = 0
filename = r"C:\tmp\TestFile.txt"
with open(filename, 'r') as f:
for line in f:
if len(line) > large_line_len:
large_line_len = len(line)
large_line = line
print large_line
output:
输出:
This Should Be Largest Line
And as a function:
作为一个函数:
def get_longest_line(filename):
large_line = ''
large_line_len = 0
with open(filename, 'r') as f:
for line in f:
if len(line) > large_line_len:
large_line_len = len(line)
large_line = line
return large_line
print get_longest_line(r"C:\tmp\TestFile.txt")
Here is another way, you would need to wrap this in a try/catch for various problems (empty file, etc).
这是另一种方法,您需要将其包装在 try/catch 中以解决各种问题(空文件等)。
def get_longest_line(filename):
mydict = {}
for line in open(filename, 'r'):
mydict[len(line)] = line
return mydict[sorted(mydict)[-1]]
You also need to decide that happens when you have two 'winning' lines with equal length? Pick first or last? The former function will return the first, the latter will return the last. File contains
您还需要确定当您有两条长度相同的“获胜”线时会发生这种情况吗?选第一个还是最后一个?前一个函数将返回第一个,后者将返回最后一个。文件包含
Small Line
Small Line
Another Small Line
This Should Be Largest Line
Small Line
Update
更新
The comment in your original post:
您原帖中的评论:
print " This program reads from a file and then prints out the"
print " line with the longest length the line ,or with the highest sum"
print " of ASCII values , or the line with the greatest number of words"
Makes me think you are going to scan the file for length of lines, then for ascii sum, then for number of words. It would probably be better to read the file once and then extract what data you need from the findings.
让我觉得你要扫描文件的行长,然后是 ascii sum,然后是字数。最好先读取一次文件,然后从结果中提取您需要的数据。
def get_file_data(filename):
def ascii_sum(line):
return sum([ord(x) for x in line])
def word_count(line):
return len(line.split(None))
filedata = [(line, len(line), ascii_sum(line), word_count(line))
for line in open(filename, 'r')]
return filedata
This function will return a list of each line of the file in the format: line, line_length, line_ascii_sum, line_word_count
此函数将以以下格式返回文件每一行的列表: line, line_length, line_ascii_sum, line_word_count
This can be used as so:
这可以这样使用:
afile = r"C:\Tmp\TestFile.txt"
for line, line_len, ascii_sum, word_count in get_file_data(afile):
print 'Line: %s, Len: %d, Sum: %d, WordCount: %d' % (
line.strip(), line_len, ascii_sum, word_count)
to output:
输出:
Line: Small Line, Len: 11, Sum: 939, WordCount: 2
Line: Small Line, Len: 11, Sum: 939, WordCount: 2
Line: Another Small Line, Len: 19, Sum: 1692, WordCount: 3
Line: This Should Be Largest Line, Len: 28, Sum: 2450, WordCount: 5
Line: Small Line, Len: 11, Sum: 939, WordCount: 2
You can mix this with Steef's solution like so:
您可以将其与 Steef 的解决方案混合使用,如下所示:
>>> afile = r"C:\Tmp\TestFile.txt"
>>> file_data = get_file_data(afile)
>>> max(file_data, key=lambda line: line[1]) # Longest Line
('This Should Be Largest Line\n', 28, 2450, 5)
>>> max(file_data, key=lambda line: line[2]) # Largest ASCII sum
('This Should Be Largest Line\n', 28, 2450, 5)
>>> max(file_data, key=lambda line: line[3]) # Most Words
('This Should Be Largest Line\n', 28, 2450, 5)
回答by Aamir
Try this:
试试这个:
def main():
print " This program reads from a file and then prints out the"
print " line with the longest length the line ,or with the highest sum"
print " of ASCII values , or the line with the greatest number of words"
length()
def length():
maxlength = 0
maxlinetext = ""
infile = open("30075165.txt","r")
for line in infile:
linelength = len(line)
if linelength > maxlength:
#If linelength is greater than maxlength value the new value is linelength
maxlength = linelength
maxlinetext = line
print maxlinetext
infile.close()
EDIT: Added main() function.
编辑:添加了 main() 函数。
回答by Nick Dandoulakis
linelength = lengthofline # bug?
It should be:
它应该是:
linelength = len(line) # fix
回答by Steven Huwig
Python might not be the right tool for this job.
Python 可能不是这项工作的正确工具。
$ awk 'length() > n { n = length(); x = import os.path
def getLongestLineFromFile(fileName):
longestLine = ""
if not os.path.exists(fileName):
raise "File not found"
file = open(fileName, "r")
for line in file:
if len(line) > len(longestLine):
longestLine = line
return longestLine
if __name__ == "__main__":
print getLongestLineFromFile("input.data")
} END { print x }' 30075165.txt
回答by Harri Siirak
My solution (also works in Python 2.5):
我的解决方案(也适用于 Python 2.5):
111111111
1111111111111111111111
111111111
22222222222222222
4444444444444444444444444444444
444444444444444
5555
Example "input.data" contents:
示例“input.data”内容:
111111111 1111111111111111111111 111111111 22222222222222222 4444444444444444444444444444444 444444444444444 5555
##代码##