![](/img/trans.png)
[英]Python Pandas does not recognize numbers when read from .txt file
[英]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.