Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将文本文件数据传递给变量_Python - Fatal编程技术网

Python 将文本文件数据传递给变量

Python 将文本文件数据传递给变量,python,Python,我正在学习python,在使用文本文件中的数据时遇到了一些麻烦 例如,文本文件的结构是逐行的,如下所示: name 656 334 _, a, b, = line.split() 我想一行一行地获取循环中的数据,并将两个整数放入两个单独的变量中,比如a=656b=334,但我很难做到这一点。我尝试了列表和numpy数组的各种迭代,但最多只能在调用数组时将这两个数字包含在一起 任何帮助都将不胜感激。您可以使用正则表达式将数字提取到数组中 此处的示例代码: 重新导入 txt=“名称656 334

我正在学习python,在使用文本文件中的数据时遇到了一些麻烦

例如,文本文件的结构是逐行的,如下所示:

name 656 334
_, a, b, = line.split()
我想一行一行地获取循环中的数据,并将两个整数放入两个单独的变量中,比如a=656b=334,但我很难做到这一点。我尝试了列表和numpy数组的各种迭代,但最多只能在调用数组时将这两个数字包含在一起


任何帮助都将不胜感激。

您可以使用正则表达式将数字提取到数组中

此处的示例代码:

重新导入
txt=“名称656 334”
x=re.findall(“[0-9]+”,txt)
打印(x)
这将返回一个包含两个值的数组

['656', '334']

然后,您只需访问数组的两个值并将其分配到一个变量中,或者仅通过访问数组来使用它

假设您的数据行格式在整个文档中是相同的,并且数据分隔符是一个空格,您可以使用split解压行数据,如下所示:

name 656 334
_, a, b, = line.split()

如果您知道每行中的所有值都将由空格分隔,则可以迭代文件中的行,并使用
split
将值放入列表中,然后相应地分配它们

with open('my_file.txt') as my_file:
    for line in my_file.readlines():
        parts = line.split()
        a = parts[1]
        b = parts[2]  # or parse it as _, a, b = line.split() as lennhv said above

逐行运行整个文件,并在空格处拆分每行。大概是这样的:

with open("your filename", "r") as f:
    lines = f.readlines()
    for line in lines:
        name, a, b = line.split()

        #Do anything with the values here

这也可以用较短的列表理解来完成,但既然你刚开始,那就应该可以了。

你也可以尝试使用Pandas。我已经用下面的代码与我的评级txt

# import pandas library
import pandas as pd
# read rating file, without header and set column name for fields
rating_df = pd.read_csv('ratings.txt', sep=' ', header=None, names =["userId", "itemId", "rating"])

for index, row in rating_df.iterrows():
    print(int(row['userId']), int(row['itemId']))
  • 遍历数据效率很低
  • 使用
    pandas.DataFrame
    ,使用矢量化操作更有效
  • pd.DataFrame.multiply
    只是一个例子。一旦数据进入
    数据框
    ,就可以执行任何功能

  • 是的,我认为
    \uuu,a,b,=line.split()
    版本更容易维护