我想从文件中分割一行,但卡住了。 假设我的文件中有这一行:
John,Smith,1580,[“cool”,“line”,“splitting”]
现在我试着这样做:
using System;
namespace crap
{
class firstClass
{
public static void Main (string[] args)
{
int choice = 0;
while (choice != 1 || choice != 2) {
Console.WriteLine ("Press 1 for choice 1 or 2 for choice for choice 2");
choice = Convert.ToInt32 (Console.ReadLine ());
if (choice == 1) {
crap.secondClass.myMethod();
}
if (choice == 2) {
}
}
}
}
public class secondClass{
public static void myMethod(int later, int later2)
{
Console.WriteLine("You chose option 1");
}
}
}
当然它会返回:
['John','Smith','1580','[“cool”','“line”','“splitting”]']
问题是文件列表。我无法正确阅读。我希望它看起来像:
['John','Smith',1580,[“cool”,“line”,“splitting”]]
有人能帮助我这样做吗?
答案 0 :(得分:3)
您可以使用ast.literal_eval
:
import ast
import re
line = 'John, Smith, 1580, ["cool","line","splitting"]'
final_line = [ast.literal_eval(i) if i.startswith('[') else int(i) if re.findall('^\d+$', i) else i for i in re.split(',\s*', line)]
输出:
['John', 'Smith', 1580, ['cool', 'line', 'splitting']]