简体   繁体   English

如何从 python 的 txt 文件的最后一列中提取数字?

[英]How do I extract the numbers from the last column in a txt file in python?

I have a file that looks like this (the last column has more or less space in between the previous one randomly):我有一个看起来像这样的文件(最后一列在前一列之间随机有或多或少的空间):

Name    LastName    Age
Adrian   Smith      101
Martin   Ville  82
Mary     Morre          9

I want to extract only the ages so I can put them inside a set.我只想提取年龄,这样我就可以把它们放在一个集合中。

I have tried this so far but I only get random one digit numbers:到目前为止我已经尝试过了,但我只得到随机的一位数字:

age = set()
for line in f:
    for i in line:
        if i.isdigit():
    age.update(i)

You are getting one digit numbers because you only check one digit at a time.您得到一位数字,因为您一次只检查一位数字。 For example, when the code reaches the first number, it will first look at "1", then "0" and then "1", and add them each as individual numbers, rather than one number: 101.例如,当代码到达第一个数字时,它会先查看“1”,然后查看“0”,然后查看“1”,并将它们分别添加为单独的数字,而不是一个数字:101。

It would be easier to split each line into a list of each word in the line, and then add the last word in the list to your set.将每一行拆分为该行中每个单词的列表,然后将列表中的最后一个单词添加到您的集合中会更容易。 You could do that with line.split(" ") (which would also leave you with a load of empty strings in the list since there are multiple spaces, but they can be ignored).您可以使用line.split(" ")来做到这一点(这也会在列表中留下大量空字符串,因为有多个空格,但可以忽略它们)。

age = set()
for idx, line in enumerate(f):
    if idx == 0:  # ignore first line
        continue
    line = line.split(" ")
    number = int(line[-1])
    age.add(number)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在python中从txt文件中提取第一个和最后一个值? - How to extract the first and last value from a txt file, in python? 如何在python中的txt文件中提取数字 - how to extract the numbers in txt file in python 如何从 .txt 文件中提取浮点值以用于 python 中的计算? - How do I extract floating point values from .txt file to use for calculation in python? 如何从巨大的txt文件中提取模式 - How do I extract the pattern out from huge txt file 如何使用python从.txt文件中提取两列? - How can I extract two columns from a .txt file with python? 如何从“对象”的 pandas 列中的字符串中提取数字? - How do I extract numbers from the strings in a pandas column of 'object'? python中将txt文件最后N行的数据提取到数组中 - Extract data from the last N lines of a txt file into arrays in python 使用 Python,如何从 PDF 中提取文本和图像 + 从 output txt 文件中提取颜色字符串和数字 - Using Python, how to extract text and images from PDF + color strings and numbers from the output txt file 如何从 txt 文件中提取字符串(数字)并使用 python 中的正则表达式转换为整数 - How to extract string (numbers) from txt file and convert to integers using regular expressions in python 如何在python中仅从txt文件中提取第一个和最后一个数值? - How to extract only the first and last numerical value from a txt file, in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM