您好我是python的新手,我有一个文本文件.txt,结构如下:
Text1 31332.22342
Text2 293023.32323
Text3 32332.32323
将这些数字放入数组的最简单方法是什么?干杯!
答案 0 :(得分:5)
您可以读取文件并将其拆分为一个列表,然后遍历列表并尝试转换为浮点数,如果成功则将其添加到浮点列表中。如下:
with open('file.txt', 'r') as f:
data = f.read().split()
floats = []
for elem in data:
try:
floats.append(float(elem))
except ValueError:
pass
print floats
输出:
[31332.22342, 293023.32323, 32332.32323]
答案 1 :(得分:2)
您还可以使用numpy genfromtxt功能。像这样的东西:
<强> text_file.txt 强>
Text1 31332.22342
Text2 293023.32323
Text3 32332.32323
python shell
>>> import numpy as np
>>> numbers = np.genfromtxt('text_file.txt', usecols=1 )
输出
[ 31332.22342 293023.32323 32332.32323]
答案 2 :(得分:0)
要获得数据类型的属性验证,请尝试以下操作:
horseman
.open(url + '' + page)
.html('article')
.then((htmlRes) => {
if(htmlRes){
var item = {}; //container for one article info
//Loading data in cheerio to parse it
var $ = cheerio.load(htmlRes);
//First step : get the title
$('h4[class=company-name]').each(function(i, elem) {
//Delete the span jobs
//Delete the number of jobs
var t = $(this).text().replace(/\s+/g, '').replace(/\d+/g, '');
//Delete the word jobs
var tRes = t.substr(0, t.length-4);
item.company = tRes;
});
var stacksF = []; //container for the list of different stacks categories
$('div[class=company-stack-category]').each(function(i, elem) {
var obj = {}; //one stack categorie
var stacks = []; //list of item in the aimed stack
obj.stackName = $(this).children('.category-title').text(); //name of the stakc
$(this).children('.company-stack-list').children('.stack-item').each(function(c, elem) {
stacks[c] = $(this).text(); //one stack element
});
var stacksRes = stacks.join(', '); //join all the stack element in a unique string
stacksRes = stacksRes.replace(/\s+/g, '');
obj.stackValue = stacksRes;
stacksF.push(obj);
});
item.stacks = stacksF;
articles.push(item);
}else{
console.log("Impossible to retrieve data");
}
})
.close();
<强>输出:强>
import numpy as np
data = np.genfromtxt("test.txt", usecols=1, dtype=float)