读取带有特殊字符的文件并将其写入html

时间:2019-06-25 15:04:58

标签: python

我有一个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
史密斯(John.pdf)

当然是哪个会打断文本和指向该pdf的链接。

如何正确编码文件或'name'变量,以便其正确写入特殊字符?
即Cabán-Sanchez,Jane.pdf

2 个答案:

答案 0 :(得分:0)

我不习惯使用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 -*-

最后,您可以尝试通过在u""行中添加f.write来显式地将字符串声明为unicode,例如:

f.write(u"...")
  

答案 1 :(得分:0)

您正在尝试将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>
相关问题