首页 > 解决方案 > 如何从仅包含数字的代码字符串中删除行,同时保留带有数字和字母的代码行?

问题描述

0
1
00:00:00,210 --> 00:00:00,930
Hey,
1

2
00:00:00,930 --> 00:00:05,280
welcome to day 50 of your course
2

3

标签: python

解决方案


查看您给出的输入,我假设有问题的文件是一个 srt 文件。0 1在这种情况下,您很可能在部分问题中犯了错误。如果是这种情况,您可以简单地使用该isnumeric()方法删除完全数字的字符串。同样的一个例子是:

f = open("infile.srt", "r")
data = f.read().splitlines()

cleaned_data = []
for eachLine in data:
    if not(eachLine.isnumeric()) and len(lineText)>1:
        cleaned_data.append(eachLine) 

print(cleaned_data)

但如果这0 1是一个常见的外观,您可以使用额外的检查条件,中间没有空格,这可以通过代码完成:

f = open("infile.srt", "r")
data = f.read().splitlines()

cleaned_data = []
for eachLine in data:
    lineText = eachLine.replace(" ", "")
    if not(lineText.isnumeric()) and len(lineText)>1:
        cleaned_data.append(eachLine) 

print(cleaned_data)

推荐阅读