问题描述
我正在尝试解析.txt文件并将其转换为JSON对象。 .txt文件如下所示:
const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
const ExtensionUtils = imports.misc.extensionUtils;
const Main = imports.ui.main;
// Here,the directory must be in ~/.local/share/gnome-shell/extensions.
function installFromLocal(uuid) {
let dir = Gio.File.new_for_path(GLib.build_filenamev([global.userdatadir,'extensions',uuid]));
let manager = Main.extensionManager;
try {
let extension = manager.createExtensionObject(uuid,dir,ExtensionUtils.ExtensionType.PER_USER);
manager.loadExtension(extension);
if (!manager.enableExtension(uuid))
throw new Error('Cannot add %s to enabled extensions gsettings key'.format(uuid));
} catch (e) {
let extension = Main.extensionManager.lookup(uuid);
if (extension)
Main.extensionManager.unloadExtension(extension);
throw new Error('Error while installing %s: %s (%s)'.format(uuid,'LoadExtensionError',e));
}
}
我想结束这样的事情:
0000000159900000000000 John Smith State Senator
0001001159915701270000DEM Jill Booker Governor
0002001159900000000000REP James Williams City Council
如果.txt文件已定界,则创建一个相对简单的循环,但没有定界。我通常要做的是这样的:
obj = {
"name": State Senator,"reporting_units": [
{
"state_postal": "IL","precincts_reporting": precincts_reporting,"total_precincts": precincts_total
"candidates": [
{
"cand_name": "John Smith","cand_id": 0000000159900000000000
}
],}
],"name": Governor,"total_precincts": precincts_total
"candidates": [
{
"cand_name": "Jill Booker","cand_id": 0001001159915701270000DEM
}
],"name": City Council,"total_precincts": precincts_total
"candidates": [
{
"cand_name": "James Williams","cand_id": 0002001159900000000000REP
}
],}
]
}
当前的问题是from bs4 import BeautifulSoup
import json
import requests
def scraper():
empty_list = []
# define object (as above)
with open('races.txt','r') as f:
data = f.readlines()
for row in data:
for item in row:
cand_id = row[0]
cand_name = row[1]
name = row[2]
# plug into object and append to list
scraper()
,row[0]
和row[1]
都为0,因为我无法用某些定界符来分隔行,因此它将一个字符读取为一项。我不知道如何编写它,以便它读取项目而不是字符。感谢您的任何帮助!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)