我已经写了一个小脚本,通过分割行"|"将文本文件转换为excel电子表格。但我得到一个列表索引超出范围的错误为lib_type = fields[4]。有人能帮我解决这个问题吗?
我的代码:
import requests
from bs4 import BeautifulSoup
import urllib.request
import xlwt
from xlwt import Workbook
file = open("apk_library_other.txt","r")
wb = Workbook() #create spreadsheet
sheet1 = wb.add_sheet('Sheet 1')
ctr = 0
for line in file:
fields = line.split("|")
app_name = fields[0]
apk = fields[1]
lib_name = fields[2]
lib_type = fields[3]
lib_permission = fields[4]
sheet1.write(ctr, 0, app_name)
sheet1.write(ctr, 1, lib_name)
sheet1.write(ctr, 2, lib_type)
sheet1.write(ctr, 3, lib_permission)
ctr += 1
#print(app_name + lib_name + lib_type)
wb.save('libraries_other.xls')
file.close()
文本文件正在被读取:
com.carenity.carenity_2020-07-16.apk|Google Mobile Services|Development Aid|android.permission.DUMP
com.carenity.carenity_2020-07-16.apk|Google Mobile Services|Development Aid|android.permission.INTERACT_ACROSS_USERS
com.carenity.carenity_2020-07-16.apk|Google Mobile Services|Development Aid|android.permission.INTERACT_ACROSS_USERS_FULL
DiseasesDictionaryTreatments.apk|Google Mobile Services|Development Aid|android.permission.BACKUP
DiseasesDictionaryTreatments.apk|Google Mobile Services|Development Aid|android.permission.BLUETOOTH_ADMIN
尝试访问列表中不存在的元素会导致IndexError
。下面的解决方案在我这边起作用了。
text.txt
com.carenity.carenity_2020-07-16.apk|Google Mobile Services|Development Aid| android.permission.DUMP
com.carenity.carenity_2020-07-16.apk|Google Mobile Services|Development Aid|android.permission.INTERACT_ACROSS_USERS
com.carenity.carenity_2020-07-16.apk|Google Mobile Services|Development Aid|android.permission.INTERACT_ACROSS_USERS_FULL
DiseasesDictionaryTreatments.apk|Google Mobile Services|Development Aid|android.permission.BACKUP
DiseasesDictionaryTreatments.apk|Google Mobile Services|Development Aid|android.permission.BLUETOOTH_ADMIN
<<p>解决方案/strong>import pandas as pd
df = pd.read_csv(
'text.txt',
sep='|', # separate by pipe
names=['apk', 'lib_name', 'lib_type', 'lib_permission']
)
# save to csv
df.to_csv('converted_text.csv', index=False)
看起来您共享的文本文件中只有4行列,但你试图访问fields[4]
,这是第五个列。