簡體   English   中英

僅讀取txt文件python中的數字

[英]Read only the numbers from a txt file python

我有一個文本文件,其中包含一些單詞和一個帶有點的數字。 例如
hello! 54.123

現在我只希望將數字54.123提取為轉換后的結果,以便結果為54123

我試過的代碼是

import re
exp = re.compile(r'^[\+]?[0-9]')

my_list = []
with open('file.txt') as f:
    lines = f.readlines()
    for line in lines:
        if re.match(exp, line.strip()):
            my_list.append(int(line.strip()))

#convert to a string
listToStr = ' '.join([str(elem) for elem in my_list])
print(listToStr)

但這會返回錯誤:ValueError:int()的無效文字,基數為10:“ 54.123”

有誰知道解決方案嗎?

這可能會幫助我現在從文件中獲取數字,我猜您正在嘗試使用split代替strip

import re
exp = re.compile(r'[0-9]')

my_list = []
with open('file.txt') as f:
    lines = f.readlines()
    for line in lines:
        for numbers in line.split():
            if re.match(exp, numbers):
                my_list.append(numbers)

#convert to a string
listToStr = ' '.join([str(elem) for elem in my_list])
print(listToStr)

您可以使用isdigit()函數檢查給定的行是否為代表數字的字符串。

據我所知,您只需要檢查是否存在一個數字,因為isdigit()僅適用於整數(浮點數包含“。”,它不是數字,並且返回False)。

例如:

def numCheck(string):
  # Checks if the input string contains numbers
  return any(i.isdigit() for i in string)

string = '54.123'
print(numCheck(string)) # True

string = 'hello'
print(numCheck(string)) # False

注意:如果您的數據包含123ab56類的123ab56那么這對您就沒有好處。


要將54.123轉換為54123,可以使用replace(old, new)函數。

例如:

string = 54.123
new_string = string.replace('.', '') # replace . with nothing
print(new_string) # 54123

您可以嘗試將當前行轉換為浮點數。 如果該行不包含合法的浮點數,則它將返回一個ValueError異常,您可以捕獲該異常並將其傳遞。 如果沒有異常,則將點處的線分開,將兩部分合並,轉換為int並添加到數組中。

my_list = []
with open('file.txt') as f:
    lines = f.readlines()
    for line in lines:
        try:
            tmp = float(line)
            num = int(''.join(line.split(".")))
            my_list.append(num)
        except ValueError:
            pass

#convert to a string
listToStr = ' '.join([str(elem) for elem in my_list])
print(listToStr)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM