簡體   English   中英

讀取帶有特殊字符的文件並將其寫入html

[英]Reading files with special characters and writing them to html

我有一個python腳本,可讀取pdf文件的名稱並將其寫入包含PDF鏈接的HTML文件中。 除非名稱包含特殊字符,否則所有方法都可以正常工作。

我已經閱讀了許多關於SE的其他答案,但無濟於事。

f = open("jobs/index.html", "w")
#html divs go here
for root, dirs, files in os.walk('jobs/'):
    files.sort()
    for name in files:
        if ((name!="index.html")&(name!=".htaccess")):
            f.write("<a href='"+name+"'>"+name.rstrip(".pdf")+"</a>\n<br><br>\n")
            print name.rstrip(".pdf")

返回值:
簡·卡巴·桑切斯(Cabañn-Sanchez).pdf
史密斯,約翰.pdf

這當然會破壞文本和該pdf的鏈接。

如何正確編碼文件或“名稱”變量,以便其正確寫入特殊字符?
即,Cabán-Sanchez,簡.pdf

我不習慣python 2.7,但這應該可以工作:

from io import open

with open("jobs/index.html", "w", encoding='utf-8') as f:
    for root, dirs, files in os.walk('jobs/'):
        files.sort()
        for name in files:
            if not name in ("index.html", ".htaccess"):
                f.write("<a href='{}'>{}</a>\n<br><br>\n".format(name, name.rstrip(".pdf")))
                print name.rstrip(".pdf")

您還應該通過在模塊頂部添加以下幾行來在python級別聲明編碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

最后,您可以嘗試通過在f.write行中添加u""將字符串顯式聲明為unicode,例如:

f.write(u"...")

您嘗試將unicode字符(在本例中為 )寫入html文件,則應指定html meta charset

<meta charset="UTF-8">

其余的都可以在我的機器上正常工作

andraantariksa@LaptopnyaAndra:~$ cd Desktop/
andraantariksa@LaptopnyaAndra:~/Desktop$ mkdir jobs
andraantariksa@LaptopnyaAndra:~/Desktop$ cd jobs/
andraantariksa@LaptopnyaAndra:~/Desktop/jobs$ touch "Cabán-Sanchez, Jane.pdf"
andraantariksa@LaptopnyaAndra:~/Desktop/jobs$ ls
'Cabán-Sanchez, Jane.pdf'
andraantariksa@LaptopnyaAndra:~/Desktop/jobs$ cd ../
andraantariksa@LaptopnyaAndra:~/Desktop$ python
Python 2.7.15+ (default, Nov 27 2018, 23:36:35) 
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> f = open("jobs/index.html", "w")
>>> #html divs go here
... for root, dirs, files in os.walk('jobs/'):
...     files.sort()
...     for name in files:
...         if ((name!="index.html")&(name!=".htaccess")):
...             f.write("<a href='"+name+"'>"+name.rstrip(".pdf")+"</a>\n<br><br>\n")
...             print name.rstrip(".pdf")
... 
Cabán-Sanchez, Jane
andraantariksa@LaptopnyaAndra:~/Desktop$ cat jobs/index.html 
<a href='Cabán-Sanchez, Jane.pdf'>Cabán-Sanchez, Jane</a>
<br><br>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM