我有一个遵循格式的文件
_line 1
this is a string on a line
_line 2
this is another string
_line 3
short line
Run Code Online (Sandbox Code Playgroud)
我正在尝试编写一些Python代码,以获取其下面字符串长度最长的字符串的_line X标签.你能帮我修改一下我的代码吗?这是我到目前为止所拥有的.
f = open('test.txt', 'r')
print f
read="null"
top_read_line_length="0"
topreadline="null"
for line in f:
checkifread=line.find('line')
if checkifread==1:
print "Read label found"
#means we are on a read line
currentread=line
else:
#We are on a sequence line for currentread.
currentlength=len(line)
print currentlength
print top_read_line_length
if int(top_read_line_length) < int(currentlength):
print topreadline
topreadline=currentread#now topreadline label is the "_line" string
topreadlinelength=int(currentlength)
print topreadline
#go to next line
print "Done"
print "Longest line is...."
print topreadline
Run Code Online (Sandbox Code Playgroud)
如果你想要的只是文件中最长的一行(就像问题标题所说的那样),那么这个在现代Python中非常简单:
>>> max(open('test.txt'), key=len)
Run Code Online (Sandbox Code Playgroud)
要获取最长行的标签,请构建标签到行长度的映射
在您的示例数据集中,看起来标签以"_line"开头,紧接着的对应行如下:
label2linelength = {}
for line in open('test.txt'):
if line.startswith('_line '):
label = line
else:
label2linelength[label] = len(line)
lastline = line
print max(label2linelength.items(), key=lambda kv: kv[1])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1134 次 |
| 最近记录: |