单行删除任何以数字开头且后面没有分隔符的行[关闭]

问题描述 投票:0回答:2

这个多行Python代码可以工作。能不能精简一点?谢谢。

temp_test_001 = '''
Test 1,2,3,
41
Test 5,6,7,
8800
8800 8800 
8800.
8800.0
8,800
Test 9,10
Test 11,12
'''.split('\n')

with open(r"temp_output_001.txt", 'w') as fp:
    for number, line in enumerate(temp_test_001):
        if not line.isalnum():
            fp.write('\n' + line) 

Test 1,2,3,
Test 5,6,7,
8800 8800 
8800.
8800.0
8,800
Test 9,10
Test 11,12
python regex windows text sed
2个回答
1
投票

这是 Python 中的一段丑陋的单行代码

txt = '''
Test 1,2,3,
41
Test 5,6,7,
8800 
8800 8800 
8800.
8800.0
8,800
Test 9, 10
Test 11, 12
'''

print('\n'.join([line for line in txt.split('\n') if not all(map(lambda x: x in '0123456789', line.strip()))]))

Test 1,2,3,
Test 5,6,7,
8800 8800 
8800.
8800.0
8,800
Test 9, 10
Test 11, 12

您可以使用

从 shell 中单行执行它
python -c "import sys; print(''.join([line for line in open(sys.argv[1]).readlines() if not all(map(lambda x: x in '0123456789', line.strip()))]))" text.txt

其中

text.txt
是您的输入文本文件。


1
投票

使用

awk

$ awk '$0 !~ /^[0-9]+$/ {print $0}' file
Test 1,2,3,
Test 5,6,7,
8800 8800
8800.
8800.0
8,800
Test 9, 10
Test 11, 12

因此,如果整行仅匹配数字,则不会打印。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.