2017-03-08 52 views
0

我使用randomuser.me API生成隨機用戶CSV文件。 程序應該將CSV轉換爲HTML表格。 我試圖跳過列[0, 3, 4]不會顯示在生成的HTML表中。 爲此,我嘗試使用for-loopif-condition。 問題是循環中的變量column不是int,我無法創建條件if (int(column) == 0 and int(column) == 3 and int(column) == 4)。 我將非常感謝指出解決方案如何解決它。將CSV文件轉換爲HTML表格時跳過列表

import webbrowser 
import csv 
import sys 
import requests 

if len(sys.argv) < 2: 
    print("Usage: project.py <htmlFile>") 
    exit(0) 

url = 'https://randomuser.me/api/?results=2&format=csv&inc=name,picture' 
with requests.Session() as s: 
    download = s.get(url) 
    decodedContent = download.content.decode('utf-8') 
    csvFile = list(csv.reader(decodedContent.splitlines(), delimiter=',')) 


# Create the HTML file 
htmlFile = open(sys.argv[1], "w") 

# Fills up HTM code 
# Remove BOM from UTF-8 (wierd symbols in the beggining of table) 
htmlFile.write('<html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><link rel="stylesheet" type="text/css" href="style.css"><head><title>Tabela</title></head><body><table>') 

# Read a single row from the CSV file 
for row in csvFile: 
    # Create a new row in the table 
    htmlFile.write('<tr>'); 
    # For each column 
    for column in row: 
     if (int(column) == 0 and int(column) == 3 and int(column) == 4): 
      continue 
     else: 
      htmlFile.write('<td>' + column + '</td>') 
    htmlFile.write('</tr>') 

htmlFile.write('</table></body></html>') 

webbrowser.open_new_tab('index.html') 

回答

0

您可以使用dellist中刪除條目。所以,按相反的順序,剛剛擺脫他們:

for c in [4,3,0]: 
    del row[c] 

重要的是要使用相反的順序,因爲從列表中刪除項目該項目後改變了一切的編號。所以總是從最後到第一。

0

我不熟悉您正在使用的RandomUser API,但在邏輯上,我不會期望它有可能爲下面的語句是正確的:

int(column) == 0 and int(column) == 3 and int(column) == 4 

可以將列等於所有這些值與此同時?似乎不太可能。我希望該列要麼是列0 列3 列4

+0

是的,你是對的。應該是或聲明。它仍然沒有解決問題。 – Daniel

0

謝謝您的幫助。

奧斯汀黑斯廷斯說,我刪除不CSV需要的列文件

for row in csvFile: 
    for column in [4,3,0]: 
     del row[column]