如何从 python 中的混合 txt 文件中读取数字
How to read numbers from a mixed txt file in python
我有一个由文本和数字组成的 txt 文件。它看起来像这样:
> this is a paragraph which is introductory which lasts
some more lines
text text text
567 45 32 468
974 35 3578 4467
325 765 355 5466
text text text
1 3 6
text text>
我需要的是存储包含 4 个数字元素的行。
当我使用读取命令时,所有元素都被读取并存储为字符串。我不确定我是否可以在不先过滤的情况下将数字转换为数字。
如有任何帮助,我将不胜感激。
谢谢
按行读取文件,并分析它们。跳过包含不相等的 4 个元素的行和不包含 4 space 个分隔整数的行:
results = []
with open (filename) as f:
for line in f:
line = line.strip().split()
if len(line) != 4:
continue # line has != 4 elements
try:
numbers = map(int,line)
except ValueError:
continue # line is not all numbers
# do something with line
results.append(line) # or append(list(numbers)) to add the integers
print(*results, sep="\n")
打印:
['567', '45', '32', '468']
['974', '35', '3578', '4467']
['325', '765', '355', '5466']
使用 splitlines() 函数。
A=open(your file here,'r').read().splitlines()
这将是一个列表,现在您可以提取您需要的任何内容。
喜欢:
Req=[]
for i in A:
elem = [s.isnumeric() for s in i.split(' ')]
if len(elem) == 4 and all(elem):
Req.append(i)
如果您可以假设您需要的行只有 4 个数字,那么这个解决方案应该可行:
nums = []
with open('filename.txt') as f:
for line in f:
line = line.split()
if len(line) == 4 and all([c.isdigit() for c in line]):
# use [float(c) for c in line] if needed
nums.append([int(c) for c in line])
print(nums)
对我来说,这听起来像是 re
模块的任务。我会这样做:
import re
with open('yourfile.txt', 'r') as f:
txt = f.read()
lines_w_4_numbers = re.findall(r'^\d+\s\d+\s\d+\s\d+$', txt, re.M)
print(lines_w_4_numbers)
输出:
['567 45 32 468', '974 35 3578 4467', '325 765 355 5466']
说明:re.M
标志意味着^
和$
将匹配行的start/end,\s
表示空白,\d+
表示1或更多位数。
因此,您要查找的子字符串 正好 由 space 分隔并以换行符结尾的四个整数。您可以使用正则表达式来定位遵循此模式的子字符串。假设您将字符串存储在变量 s
:
中
import re
matches = [m[0] for m in re.findall(r"((\d+\s){4})", s)]
matches
变量现在包含恰好包含四个整数的字符串。之后,如果需要,您可以拆分每个字符串并转换为整数:
matches = [[int(i) for i in s.split(' ')] for s in matches]
结果:
[[567, 45, 32, 468], [974, 35, 3578, 4467], [325, 765, 355, 5466]]
如果您知道如何使用 python 正则表达式模块,您可以这样做:
import re
if __name__ == '__main__':
with open(TEST_FILE, 'r') as file_1:
for line in file_1.readlines():
if re.match(r'(\d+\s){4}', line):
line = line.strip() # remove \n character
print(line) # just lines with four numbers are printed
您的文件示例的结果是:
567 45 32 468
974 35 3578 4467
325 765 355 5466
这里使用正则表达式将是最强大的。我们使用 re.compile 创建一个模式,然后我们使用搜索或匹配方法来匹配字符串中的模式。
import re
p = re.compile(r'[\d]{4}') # \d matches for single digit and {4} will look for 4 continuous occurrences.
file = open('data.txt', 'r') # Opening the file
line_with_digits = []
for line in file: # reading file line by line
if p.search(line): # searching for pattern in line
line_with_digits.append(line.strip()) # if pattern matches adding to list
print(line_with_digits)
上述程序的输入文件是:
text text text
567 45 32 468
974 35 3578 4467
325 765 355 5466
text text text
1 3 6
text text
text 5566 text 45 text
text text 564 text 458 25 text
输出为:
['974 35 3578 4467', '325 765 355 5466', 'text 5566 text 45 text']
希望对您有所帮助。
你可以使用正则表达式:
import re
result = []
with open('file_name.txt') as fp:
for line in fp.readlines():
if re.search(r'\d{4}', line):
result.append(line.strip())
print(result)
输出:
['974 35 3578 4467', '325 765 355 5466']
我有一个由文本和数字组成的 txt 文件。它看起来像这样:
> this is a paragraph which is introductory which lasts
some more lines
text text text
567 45 32 468
974 35 3578 4467
325 765 355 5466
text text text
1 3 6
text text>
我需要的是存储包含 4 个数字元素的行。
当我使用读取命令时,所有元素都被读取并存储为字符串。我不确定我是否可以在不先过滤的情况下将数字转换为数字。
如有任何帮助,我将不胜感激。 谢谢
按行读取文件,并分析它们。跳过包含不相等的 4 个元素的行和不包含 4 space 个分隔整数的行:
results = []
with open (filename) as f:
for line in f:
line = line.strip().split()
if len(line) != 4:
continue # line has != 4 elements
try:
numbers = map(int,line)
except ValueError:
continue # line is not all numbers
# do something with line
results.append(line) # or append(list(numbers)) to add the integers
print(*results, sep="\n")
打印:
['567', '45', '32', '468']
['974', '35', '3578', '4467']
['325', '765', '355', '5466']
使用 splitlines() 函数。
A=open(your file here,'r').read().splitlines()
这将是一个列表,现在您可以提取您需要的任何内容。 喜欢:
Req=[]
for i in A:
elem = [s.isnumeric() for s in i.split(' ')]
if len(elem) == 4 and all(elem):
Req.append(i)
如果您可以假设您需要的行只有 4 个数字,那么这个解决方案应该可行:
nums = []
with open('filename.txt') as f:
for line in f:
line = line.split()
if len(line) == 4 and all([c.isdigit() for c in line]):
# use [float(c) for c in line] if needed
nums.append([int(c) for c in line])
print(nums)
对我来说,这听起来像是 re
模块的任务。我会这样做:
import re
with open('yourfile.txt', 'r') as f:
txt = f.read()
lines_w_4_numbers = re.findall(r'^\d+\s\d+\s\d+\s\d+$', txt, re.M)
print(lines_w_4_numbers)
输出:
['567 45 32 468', '974 35 3578 4467', '325 765 355 5466']
说明:re.M
标志意味着^
和$
将匹配行的start/end,\s
表示空白,\d+
表示1或更多位数。
因此,您要查找的子字符串 正好 由 space 分隔并以换行符结尾的四个整数。您可以使用正则表达式来定位遵循此模式的子字符串。假设您将字符串存储在变量 s
:
import re
matches = [m[0] for m in re.findall(r"((\d+\s){4})", s)]
matches
变量现在包含恰好包含四个整数的字符串。之后,如果需要,您可以拆分每个字符串并转换为整数:
matches = [[int(i) for i in s.split(' ')] for s in matches]
结果:
[[567, 45, 32, 468], [974, 35, 3578, 4467], [325, 765, 355, 5466]]
如果您知道如何使用 python 正则表达式模块,您可以这样做:
import re
if __name__ == '__main__':
with open(TEST_FILE, 'r') as file_1:
for line in file_1.readlines():
if re.match(r'(\d+\s){4}', line):
line = line.strip() # remove \n character
print(line) # just lines with four numbers are printed
您的文件示例的结果是:
567 45 32 468
974 35 3578 4467
325 765 355 5466
这里使用正则表达式将是最强大的。我们使用 re.compile 创建一个模式,然后我们使用搜索或匹配方法来匹配字符串中的模式。
import re
p = re.compile(r'[\d]{4}') # \d matches for single digit and {4} will look for 4 continuous occurrences.
file = open('data.txt', 'r') # Opening the file
line_with_digits = []
for line in file: # reading file line by line
if p.search(line): # searching for pattern in line
line_with_digits.append(line.strip()) # if pattern matches adding to list
print(line_with_digits)
上述程序的输入文件是:
text text text
567 45 32 468
974 35 3578 4467
325 765 355 5466
text text text
1 3 6
text text
text 5566 text 45 text
text text 564 text 458 25 text
输出为:
['974 35 3578 4467', '325 765 355 5466', 'text 5566 text 45 text']
希望对您有所帮助。
你可以使用正则表达式:
import re
result = []
with open('file_name.txt') as fp:
for line in fp.readlines():
if re.search(r'\d{4}', line):
result.append(line.strip())
print(result)
输出:
['974 35 3578 4467', '325 765 355 5466']