[英]How can I remove lines of a file that don't contain a number?
I have a file containing lines that look like this: 我有一个包含如下行的文件:
43
763
hello
4903
world
2632
hello 382
I need to strip every line which doesn't contain a number. 我需要剥离不包含数字的每一行。 That means the line can stay if it contains a string but only if it also contains any number. 这意味着如果该行包含一个字符串,但仅当它也包含任何数字时,该行才能保留。
The output would be: 输出为:
43
763
4903
2632
hello 382
edit: So now I've got 编辑:所以现在我有
with open('numstest.txt') as oldfile, open('numtest2.txt', 'w') as newfile:
for line in oldfile:
if not line.isalpha():
newfile.write(line)
But for some reason, it's outputting the file exactly the same. 但是由于某种原因,它输出的文件完全相同。
Just use a regular expression as follows 只需使用正则表达式如下
s = """43
763
hello
4903
world
2632
hello 382"""
p = re.compile(r"\d")
lines = (line for line in s.splitlines() if p.search(line))
for line in lines:
print(line)
43
763
4903
2632
hello 382
See if it works for you. 看看是否适合您。
Add all your strings to a list and print only the correct strings using the isalpha()
method. 将所有字符串添加到列表中,并使用isalpha()
方法仅打印正确的字符串。
ls = ["43","763","hello","4903","world","2632","hello 382"]
for i in ls:
if not i.isalpha():
print(i)
EDIT : To get the file IO right, strip the newline character from a line before you check, so something like this: 编辑 :要正确获取文件IO,请在检查之前从一行中删除换行符,如下所示:
with open('numstest.txt') as oldfile, open('numtest2.txt', 'w') as newfile:
for line in oldfile:
if not line.strip().isalpha():
newfile.write(line)
The strip
method removes the whitespace characters from both ends of a string so that you get the string "hello"
for example, instead of "hello\\n"
strip
方法从字符串的两端删除空格字符,以便获得字符串"hello"
,而不是"hello\\n"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.