在Python中读取文件并将内容分配给变量

2024-03-29 11:32:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个文本文件中有一个ECC键值,我想将该值赋给一个变量以供进一步使用的一组行。虽然我可以从文件中读取键值,但我不知道如何将该值赋给变量。我不想把它当作一个数组。例如

变量=读取(public.txt)。

有什么建议吗?

python版本是3.4


Tags: 版本txt数组public建议键值文本文件ecc
2条回答

使用带有正则表达式的捕获组可以完美地捕获字符串中的特定数据

  String str = "Locaton;RowIndex;maxRows=New York, NY_10007;1;4 ";
   String pattern = "(.*?=)(.*?)(,.*)";
   Pattern r = Pattern.compile(pattern);

   Matcher m = r.matcher(str);

   if (m.find()) {
       System.out.println("Group 1: " + m.group(1));
       System.out.println("Group 2: " + m.group(2));
       System.out.println("Group 3: " + m.group(3));
   }

这是输出

Group 1: Locaton;RowIndex;maxRows=
Group 2: New York
Group 3: , NY_10007;1;4 

尝试如下使用此正则表达式"=(.*?),"

   String str = "Locaton;RowIndex;maxRows=New York, NY_10007;1;4 ";
    Pattern pattern = Pattern.compile("=(.*?),");
    Matcher matcher = pattern.matcher(str);
    if (matcher.find()) {
        System.out.println(matcher.group(1));
    }

输出:

   New York

Using matcher.group(1) means capturing groups make it easy to extract part of the regex match,parentheses also create a numbered capturing group. It stores the part of the string matched by the part of the regular expression inside the parentheses.

 Match "Locaton;RowIndex;maxRows=New York, NY_10007;1;4 "
 Group 1: "New York"

相关问题 更多 >