惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
DataBreaches.Net
Apple Machine Learning Research
Apple Machine Learning Research
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
S
SegmentFault 最新的问题
博客园 - 聂微东
罗磊的独立博客
W
WeLiveSecurity
博客园_首页
Scott Helme
Scott Helme
V
Visual Studio Blog
T
The Exploit Database - CXSecurity.com
G
Google Developers Blog
大猫的无限游戏
大猫的无限游戏
Latest news
Latest news
L
Lohrmann on Cybersecurity
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
About on SuperTechFans
F
Full Disclosure
Y
Y Combinator Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
博客园 - 司徒正美
博客园 - Franky
C
CXSECURITY Database RSS Feed - CXSecurity.com
F
Fortinet All Blogs
Blog — PlanetScale
Blog — PlanetScale
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
阮一峰的网络日志
阮一峰的网络日志
S
Schneier on Security
雷峰网
雷峰网
博客园 - 【当耐特】
P
Privacy International News Feed
C
Cyber Attacks, Cyber Crime and Cyber Security
Engineering at Meta
Engineering at Meta
aimingoo的专栏
aimingoo的专栏
MongoDB | Blog
MongoDB | Blog
J
Java Code Geeks
T
Tor Project blog
V
V2EX
爱范儿
爱范儿
C
Check Point Blog
T
Threatpost
Project Zero
Project Zero
量子位
V
Vulnerabilities – Threatpost
Know Your Adversary
Know Your Adversary
I
Intezer
G
GRAHAM CLULEY
P
Privacy & Cybersecurity Law Blog
GbyAI
GbyAI
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com

夜行人

回家路上 第一期的直播演示项目 震动检测器 正能量 在线参观CodeLab Neverland 发布 CodeLab Adapter 3.3.1 DynamicTable 之 纸糊方向盘 CodeLab DynamicTable: 一个可实施的技术方案 CodeLab Insight 发布 Alpha 版 情人节 Home Assistant 周报 && IoT 周报 (02) Joplin: 关注隐私的 Evernote 开源替代软件 浏览器的未来与 Web 传感器 Home Assistant 周报 && IoT 周报 (01) 百宝箱(01) 论自由 介绍 WebThings Home Assistant 周报 && iot 周报 (00) 百宝箱(00) 毛姆读书心得 传世之作 周末徒步 CodeLab Adapter ❤️ Jupyter/Python 航班 躲雨 夏令营途中 [译]思想--作为一种技术 The future of coding 美国之行 三门问题的程序模拟 从Python转向Pharo https://blog.just4fun.site/post/iot/iot-open-source-projects/ Python异步编程笔记 https://blog.just4fun.site/post/iot/iot-open-source-hardware-community/ 万物积木化开发者社区 CodeLab ❤️ Blender Scratch3技术分析之云变量 API(第7篇) [译]对管道(Pipes)的偏爱 [译]提出正确的问题比得到正确答案更重要 蓝牙设备与Scratch3.0 创建你的第一个Scratch3.0 Extension Scratch3技术分析之项目内部数据(第6篇) Scratch3技术分析之社区 API(第5篇) Scratch3技术分析之User API(第4篇) Scratch3技术分析之项目主页API(第3篇) Scratch3技术分析之静态资源API(第2篇) Scratch3.0、micro:bit与Windows7 https://blog.just4fun.site/post/iot/zerynth-vs-micropython/ 核聚变、方所与半宅空间 可视化编程为何是个糟糕的主意 codelab.club周末聚会 关于codelab.club '下一件大事'是一个房间 Hungry Robot - Eat everything 编程作为一种思考方式 今日简史 史蒂夫·乔布斯传 罗素自选文集 https://blog.just4fun.site/post/edx/tianjin-scratch-ai/ https://blog.just4fun.site/post/edx/richie-cms-openedx/ 徒步武功山 WebUSB与micro:bit 积木化编程与3D场景 夜宿武功山顶 scratch3-adapter接入优必选Alpha系列机器人 https://blog.just4fun.site/post/edx/video-migration-note/ scratch3-adapter重构笔记 https://blog.just4fun.site/post/edx/edx-community-members/ 两种硬件编程风格的比较 使用micro:bit自制PPT翻页笔 柏拉图对话集 scratch3.0 + micro:bit 七月电影放映计划 非营利组织的管理 Screenly--用树莓派让任何屏幕变为可编程的数字标牌 以最佳实践开始你的Django项目 micro:bit与事件驱动 为Scratch3.0设计的插件系统(上篇) OCR应用一例 近两年读过的一些好书 blockly开发之使用python驱动浏览器中的turtle(2) 牛顿新传 文学理论入门 逻辑的引擎 人生的意义 blockly开发之生成并运行js代码(1) blockly开发之hello world(0) micro:bit使用笔记 神器之Termux https://blog.just4fun.site/post/iot/micropython-notes/ Cozmo what is this Scratch的前世今生 下段旅程 我行在远方 爆裂 途中杂记 https://blog.just4fun.site/post/edx/open-edx-startup/ cozmo系列之入门 - 有性格且可编程的机器人 PaperWeekly开发笔记 创业二三事
正则表达式之处理一组lrc听力文件
2015-05-22 · via 夜行人

我觉得可以写一个「室友需求」系列的文章了 ^_^

工作缘故,室友时常会处理一些文本文件,手动编辑不胜其烦,于是我又可以有秀代码的机会啦!

看着自己十几分钟写的代码,能在生产实际中被使用,并且给人家节约大量的时间,嘚瑟的不行啊简直!

#需求描述 此次的任务是处理一批lrc文件:

  • 转化时间的格式,将[分钟:秒]转化为
  • 每一个句子前头时间应当包含始末
  • 输出txt格式的文件

##待处理文本

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
:::text
[00:00.12]section 2.
[00:02.68]you will part of a radio programme about the opening of a new local sports shop.
[00:09.32]first you have some time to look at questions 11 to 16.
[00:39.64]now listen carefully and answer questions 11 to 16.
[00:48.24]now we go to Jane who is going to tell us about what's happening in town this weekend.
[00:52.24]right,thanks Andrew,
[00:53.92]and now on to what's new,
[00:56.48]and do we really need yet another sports shop in Bradcaster?
[01:01.24]well,most of you probably know Sports World-
[01:04.44]the branch of a Danish sports goods company that opened a few years ago-
[01:09.04]it's attracted a lot of custom,
[01:11.36]and so the company has now decided to open another branch in the area.
[01:16.60]it's going to be in the shopping centre to the west of Bradcaster,
[01:20.44]so that will be good news for all of you who've found the original shop in the north of the town hard to get to.
[01:27.12]i was invited to a special preview
[01:29.60]and i can promise you,this is the ultimate in sports retailing.
......

##目标格式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
:::text
0.12      2.68   section 2.
2.68      9.32   you will part of a radio programme about the opening of a new local sports shop.
9.32     39.64   first you have some time to look at questions 11 to 16.
39.64    48.24   now listen carefully and answer questions 11 to 16.
48.24    52.24   now we go to Jane who is going to tell us about what's happening in town this weekend.
52.24    53.92   right,thanks Andrew,
53.92    56.48   and now on to what's new,
56.48    61.24   and do we really need yet another sports shop in Bradcaster?
61.24    64.44   well,most of you probably know Sports World-
64.44    69.04   the branch of a Danish sports goods company that opened a few years ago-
69.04    71.36   it's attracted a lot of custom,
71.36    76.60   and so the company has now decided to open another branch in the area.
76.60    80.44   it's going to be in the shopping centre to the west of Bradcaster,
80.44    87.12   so that will be good news for all of you who've found the original shop in the north of the town hard to get to.
87.12    89.60   i was invited to a special preview
89.60    94.88   and i can promise you,this is the ultimate in sports retailing.
......

#思路 这种问题当然是用正则表达式来解决。比较目标文本格式和待处理文本格式,我们发现,上下两行间需要关联处理,而正则表达式一般是以一行为处理单位的。

我把这个问题转化为列表迭代的问题。之后匹配替换。all in code。直接读代码吧

#解决方案(Python版)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/env python
# encoding: utf-8
import re
import os
import sys
from decimal import Decimal as D

def filter_filetype(path,filetype):
    filetype = filetype.lower()
    filenames = [filename for filename in os.listdir(path)
        if os.path.isfile(os.path.join(path, filename))] #Get all regular files
    filter_filename_list = [filename for filename in filenames if filename.endswith(filetype)]
    return filter_filename_list

def min_sec_str2sec_str(min_sec_str):
    '''minute:second change to second'''
    (m,s) = min_sec_str.split(":")
    sec = 60*D(m)+D(s)
    sec_str = str(sec)
    return sec_str

def format_file_time(filename):
    with open(filename,"r") as input_file:
        content = input_file.read()
        thetime = re.compile(r"\[(\d{2}:.{5})\]")
        #match is list: ['00:00.12',...]
        match = thetime.findall(content)
        sec_strs = [min_sec_str2sec_str(min_sec_str) for min_sec_str in match ]
        #再一次推导,使其成为新的格式,注意边界
        new_format = ["{:<6s}  {:>6s}   ".format(sec_str,sec_strs[i+1]) for i,sec_str in enumerate(sec_strs) if i<len(sec_strs)-1] #最后一行是边界
        #单独添加最后一行
        #new_format.append(sec_strs[-1])#list本身被改变了
        #print new_format
        #exit()
    filename_split = filename.split(".")
    #后缀改为txt
    out_filename = filename_split[0]+"_output.txt"
    output_file = open(out_filename,"w")
    with open(filename,"r") as input_file:
        i = 0 #行号标记
        for line in input_file:
            if i==len(sec_strs)-1:
                #最后一行不要
                break
            result_line = thetime.sub(new_format[i],line)
            #print result_line
            output_file.write(result_line)
            i = i+1
    output_file.close()
    
if __name__ == "__main__":
    path = sys.argv[1]
    filetype = sys.argv[2]
    filter_filename_list = filter_filetype(path,filetype)
    for filename in filter_filename_list:
        print(os.path.join(path,filename))
        format_file_time(os.path.join(path,filename))
        #注意路径

使用:python3 two_line_time.py PATH lrc (PATH是你要处理的lrc文件的路径,请使用绝对路径!)

室友说这段代码可能会挺有用,目前网上下载到的多是这类lrc,需要这样转化后才能被软件读取。

在OS X 和ubuntu下测试都正常

用得着的同学就自取吧~

文章作者 种瓜

上次更新 2015-05-22