jQuery火箭图标返回顶部代码

遇到一个具体点的任务,一个同学让帮忙做个文件信息提取脚本,文本文件中有很多行(二十几万),每行有三列,用空格隔开,提取第一列和第三列,中间的空行必须要保存到新文件中,部分文本如下:

Confidence NN B-NP
in IN B-PP
the DT B-NP
pound NN I-NP
is VBZ B-VP
widely RB I-VP
expected VBN I-VP
to TO I-VP
take VB I-VP

another DT B-NP
sharp JJ I-NP
dive NN I-NP
if IN B-SBAR
trade NN B-NP
figures NNS I-NP

for IN B-PP
September NNP B-NP
, , O
 
有两种方法,第一种是逐行读取文件到list中,然后删除list中的第二个元素,把list转为字符串的形式(列表转字符串需要用到join函数),并用空格分离,然后存入新文件中,开始的时候比较难处理的是空行,遇到空行进行元素删除的时候会越界,因为空行被转为了空的list,只需要加个判断就行了。程序并不长,但是真的要解决问题还是花了不少时间,具体代码如下:
# 将一个文件中的第二列删除,(遇到空行时保持不变)然后存入到另一个文件中
f = open('train2.txt')


while True:
    lines = f.readline()
   # print(line)
   # w = open('result.txt','w+')
    s = lines.split()
    if len(s):
        
        del s[1]
        print(s)
        s1 = " ".join(str(i) for i in s)
        with open('result2.txt','a') as mon:
            mon.write(s1+'
')
    else:
        
        with open('result2.txt','a') as mon:
            
            mon.write('
')
     
f.close()

第二种办法是直接提取第一列和第三列,这种方法看起来还要简单一些。

f = open("train.txt","r")

lines = f.readlines();
for line in lines:
    linea = line.split(' ')
    if len(linea)==3:
        print(linea[0],linea[2])
    else:
        print("
")

    with open('result.txt','a') as f:
        if len(linea) == 3:
            f.write(str(linea[0])+' '+str(linea[2]))

        else:
            f.write('
')
 
原文地址:https://www.cnblogs.com/libai123456/p/9771138.html