简体   繁体   English

如何从csv文件读取数据并将数据插入html文件

[英]How to read in data from a csv file and insert the data into an html file

I'm trying to create a Python script that will (a) read a csv file with data, (b) take that data and insert it into specific tags of an html string, (c) and finally write that modified html string to an html file. 我正在尝试创建一个Python脚本,该脚本将(a)读取包含数据的csv文件,(b)获取该数据并将其插入到html字符串的特定标记中,(c)最后将修改后的html字符串写入到html文件。

So far, I have the script to read in from a csv file here: 到目前为止,我具有从此处的csv文件读取的脚本:

import csv

with open('data.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        print row

f.close()

I also have the script that will write an html file here: 我也有将在此处写入html文件的脚本:

import webbrowser

# open blank file
f = open('template.html', 'w')

message = """<style scoped="scoped" type="text/css">h1.page-title { display: none; }</style>

<p>&nbsp;</p>

<div class="row">
    <div class="col-xs-12 col-sm-8 col-md-9">
        <div class="twoblocks">
            <div class="blocks-holder grey">

                <div class="block-left w50 bkgimage" style="background-image: url('/images/common/not_pictured-wide.jpg');">
                    <div class="force-16x9">&nbsp;</div>
                </div>

                <div class="block-right w50 content" style="width: 50%;">
                <h1>Dr. Rosen Rosen</h1>
                <span class="superhead">Title, <a href="index.php?Itemid=XXXX">Department</a></span>
                </div>

            </div>
        </div>

        <h3>Biography</h3>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam hendrerit mauris dictum metus porta, in consectetur dui aliquam. Nunc eu pharetra ipsum. Donec nec tincidunt dolor. Mauris dolor nisi, pellentesque quis tellus malesuada, placerat tristique dui. Phasellus at dui in nunc vestibulum accumsan. Aliquam erat volutpat. Duis non interdum ipsum, et tristique leo. Pellentesque condimentum, felis id placerat placerat, purus purus mattis urna, ac sodales ipsum ipsum ut risus. Aenean eget molestie ante, nec blandit magna. Integer efficitur fringilla odio sit amet sagittis. Sed ante turpis, pulvinar condimentum vehicula ac, tempus cursus ante. Donec eu scelerisque metus. Vestibulum facilisis tincidunt fermentum. Phasellus consequat odio in libero pharetra rutrum.</p>

        <hr />

        <h3>Education</h3>
        <ul class="list-unstyled list-spaced">
            <li>Ph.D., Field of Degree, University of Lorem Ipusm, 1990</li>
            <li>M.S., Field of Degree, University of Lorem Ipusm, 1990</li>
            <li>B.S., Field of Degree, University of Lorem Ipusm, 1990</li>
        </ul>

        <hr />

        <h3>Classes Taught</h3>
        <ul class="list-unstyled list-spaced">
            <li><a target="_blank" href="http://catalog.example.com/search/?search=CLA+###">CLA ### - First Class</a></li>
            <li><a target="_blank" href="http://catalog.example.com/search/?search=CLA+###">CLA ### - Second Class</a></li>
            <li><a target="_blank" href="http://catalog.example.com/search/?search=CLA+###">CLA ### - Third Class</a></li>
        </ul>

        <div id="classes" class="collapse">

            <ul class="list-unstyled list-spaced top-0">
                <li><a target="_blank" href="http://catalog.example.com/search/?search=CLA+###">CLA ### - Fourth Class</a></li>
                <li><a target="_blank" href="http://catalog.example.com/search/?search=CLA+###">CLA ### - Fifth Class</a></li>
                <li><a target="_blank" href="http://catalog.example.com/search/?search=CLA+###">CLA ### - Sixth Class</a></li>
            </ul>

        </div>

        <button type="button" class="btn btn-default expand collapsed" data-toggle="collapse" data-target="#classes"></button>

        <hr />

        <h3>Affiliations</h3>
        <ul class="list-unstyled list-spaced">
            <li>Organization</li>
            <li>Organization</li>
            <li>Organization</li>
        </ul>

        <div id="affiliations" class="collapse">

            <ul class="list-unstyled list-spaced top-0">
                <li>Organization</li>
                <li>Organization</li>
                <li>Organization</li>
            </ul>

        </div>

        <button type="button" class="btn btn-default expand collapsed" data-toggle="collapse" data-target="#affiliations"></button>

        <hr />

        <h3>Publications</h3>
        <ul class="list-unstyled list-spaced">
            <li>"Article Title." <em>Name of Publication.</em> Volume, Page Numbers. Authors (Date).</li>
            <li>"Article Title." <em>Name of Publication.</em> Volume, Page Numbers. Authors (Date).</li>
            <li>"Article Title." <em>Name of Publication.</em> Volume, Page Numbers. Authors (Date).</li>
        </ul>

        <div id="publications" class="collapse">

            <ul class="list-unstyled list-spaced top-0">
                <li>"Article Title." <em>Name of Publication.</em> Volume, Page Numbers. Authors (Date).</li>
                <li>"Article Title." <em>Name of Publication.</em> Volume, Page Numbers. Authors (Date).</li>
                <li>"Article Title." <em>Name of Publication.</em> Volume, Page Numbers. Authors (Date).</li>
            </ul>

        </div>

        <button type="button" class="btn btn-default expand collapsed" data-toggle="collapse" data-target="#publications"></button>

    </div>

    <aside class="col-xs-12 col-sm-4 col-md-3">
        <div class="well">

            <h3>Contact</h3>
            <p>Address <br />Building Name <br />Room # <br />City, State, Zip <br /> <a href="/map"><i class="ico-map"></i>Map</a></p>
            <p><i class="ico-phone"></i> XXX.XXX.XXXX <br /> <a href="mailto:">name@example.com</a></p>
        </div>

        <h3>Academic Interests</h3>
        <ul class="list-unstyled list-spaced">
            <li>Area</li>
            <li>Another Area</li>
            <li>Area</li>
            <li>Another Area</li>
        </ul>

    </aside>

</div>"""

# write to file
f.write(message)

# close file
f.close()

# open in browser
filename = 'file:////Scripts/' + 'template.html'
webbrowser.open_new_tab(filename)

So as of now, I can read in information from a csv file, and I can also create an html file with the template I'm using. 因此,到目前为止,我可以从csv文件读取信息,也可以使用正在使用的模板创建html文件。 Where I'm stuck, is how to take that csv information and stick that information into the html in a specific order in the tags. 我遇到的问题是如何获取该csv信息并将该信息按标签中的特定顺序粘贴到html中。

For example, each row in the csv has the information to fill out the html template. 例如,csv中的每一行都有填写HTML模板的信息。 Basically, the first column contains the 'name' for the <h1>Dr. Rosen Rosen</h1> 基本上,第一列包含<h1>Dr. Rosen Rosen</h1>的“名称” <h1>Dr. Rosen Rosen</h1> <h1>Dr. Rosen Rosen</h1> , the next column has the 'title' for <span class="superhead">Title, , and so on down through the html. <h1>Dr. Rosen Rosen</h1> ,下一列具有<span class="superhead">Title,依此类推,直到整个html。

This script is basically allowing me to use a csv with a bunch of information and build a webpage so that I don't have to continually go into the code and manually enter it. 基本上,该脚本使我可以使用带有大量信息的csv并构建网页,从而无需不断输入代码并手动输入代码。 I'm just having a problem figuring out how to get this script to do what I want it to do since I'm relatively new to Python. 由于我是Python的新手,因此我在弄清楚如何使此脚本执行我想要的功能时遇到了问题。

Any help or suggestions are appreciated. 任何帮助或建议,表示赞赏。

You need to combine your scripts into one script. 您需要将脚本合并为一个脚本。 For each row in the csv file you extract the data for that doctor then you use string concatenation to splice it with the ginormous html string. 对于csv文件中的每一行,您提取该医生的数据,然后使用字符串串联将其与html巨大的字符串拼接在一起。 Then you write that string to the output file. 然后,将该字符串写入输出文件。

Below is a sample that outputs the name, title, and department data. 下面是一个输出名称,职务和部门数据的示例。

However, I have to agree with @TankorSmash that this may not be the best solution. 但是,我必须同意@TankorSmash,这可能不是最佳解决方案。 Some kind of templating engine is usually easier to work with. 某种模板引擎通常更易于使用。

import webbrowser
import csv

# open blank file
f = open('template.html', 'w')


with open('./data.csv', 'r') as c:
    reader = csv.reader(c)
    for row in reader:
        name = row[0]
        title = row[1]
        department = row[2]

        message = """<style scoped="scoped" type="text/css">h1.page-title { display: none; }</style>

<p>&nbsp;</p>

<div class="row">
    <div class="col-xs-12 col-sm-8 col-md-9">
        <div class="twoblocks">
            <div class="blocks-holder grey">

                <div class="block-left w50 bkgimage" style="background-image: url('/images/common/not_pictured-wide.jpg');">
                    <div class="force-16x9">&nbsp;</div>
                </div>

                <div class="block-right w50 content" style="width: 50%;">
                <h1>""" + name + """</h1>
                <span class="superhead">""" + title + """, <a href="index.php?Itemid=XXXX">""" + department + """</a></span>
                </div>

            </div>
        </div>

        <h3>Biography</h3>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam hendrerit mauris dictum metus porta, in consectetur dui aliquam. Nunc eu pharetra ipsum. Donec nec tincidunt dolor. Mauris dolor nisi, pellentesque quis tellus malesuada, placerat tristique dui. Phasellus at dui in nunc vestibulum accumsan. Aliquam erat volutpat. Duis non interdum ipsum, et tristique leo. Pellentesque condimentum, felis id placerat placerat, purus purus mattis urna, ac sodales ipsum ipsum ut risus. Aenean eget molestie ante, nec blandit magna. Integer efficitur fringilla odio sit amet sagittis. Sed ante turpis, pulvinar condimentum vehicula ac, tempus cursus ante. Donec eu scelerisque metus. Vestibulum facilisis tincidunt fermentum. Phasellus consequat odio in libero pharetra rutrum.</p>

        <hr />

        <h3>Education</h3>
        <ul class="list-unstyled list-spaced">
            <li>Ph.D., Field of Degree, University of Lorem Ipusm, 1990</li>
            <li>M.S., Field of Degree, University of Lorem Ipusm, 1990</li>
            <li>B.S., Field of Degree, University of Lorem Ipusm, 1990</li>
        </ul>

        <hr />

        <h3>Classes Taught</h3>
        <ul class="list-unstyled list-spaced">
            <li><a target="_blank" href="http://catalog.example.com/search/?search=CLA+###">CLA ### - First Class</a></li>
            <li><a target="_blank" href="http://catalog.example.com/search/?search=CLA+###">CLA ### - Second Class</a></li>
            <li><a target="_blank" href="http://catalog.example.com/search/?search=CLA+###">CLA ### - Third Class</a></li>
        </ul>

        <div id="classes" class="collapse">

            <ul class="list-unstyled list-spaced top-0">
                <li><a target="_blank" href="http://catalog.example.com/search/?search=CLA+###">CLA ### - Fourth Class</a></li>
                <li><a target="_blank" href="http://catalog.example.com/search/?search=CLA+###">CLA ### - Fifth Class</a></li>
                <li><a target="_blank" href="http://catalog.example.com/search/?search=CLA+###">CLA ### - Sixth Class</a></li>
            </ul>

        </div>

        <button type="button" class="btn btn-default expand collapsed" data-toggle="collapse" data-target="#classes"></button>

        <hr />

        <h3>Affiliations</h3>
        <ul class="list-unstyled list-spaced">
            <li>Organization</li>
            <li>Organization</li>
            <li>Organization</li>
        </ul>

        <div id="affiliations" class="collapse">

            <ul class="list-unstyled list-spaced top-0">
                <li>Organization</li>
                <li>Organization</li>
                <li>Organization</li>
            </ul>

        </div>

        <button type="button" class="btn btn-default expand collapsed" data-toggle="collapse" data-target="#affiliations"></button>

        <hr />

        <h3>Publications</h3>
        <ul class="list-unstyled list-spaced">
            <li>"Article Title." <em>Name of Publication.</em> Volume, Page Numbers. Authors (Date).</li>
            <li>"Article Title." <em>Name of Publication.</em> Volume, Page Numbers. Authors (Date).</li>
            <li>"Article Title." <em>Name of Publication.</em> Volume, Page Numbers. Authors (Date).</li>
        </ul>

        <div id="publications" class="collapse">

            <ul class="list-unstyled list-spaced top-0">
                <li>"Article Title." <em>Name of Publication.</em> Volume, Page Numbers. Authors (Date).</li>
                <li>"Article Title." <em>Name of Publication.</em> Volume, Page Numbers. Authors (Date).</li>
                <li>"Article Title." <em>Name of Publication.</em> Volume, Page Numbers. Authors (Date).</li>
            </ul>

        </div>

        <button type="button" class="btn btn-default expand collapsed" data-toggle="collapse" data-target="#publications"></button>

    </div>

    <aside class="col-xs-12 col-sm-4 col-md-3">
        <div class="well">

            <h3>Contact</h3>
            <p>Address <br />Building Name <br />Room # <br />City, State, Zip <br /> <a href="/map"><i class="ico-map"></i>Map</a></p>
            <p><i class="ico-phone"></i> XXX.XXX.XXXX <br /> <a href="mailto:">name@example.com</a></p>
        </div>

        <h3>Academic Interests</h3>
        <ul class="list-unstyled list-spaced">
            <li>Area</li>
            <li>Another Area</li>
            <li>Area</li>
            <li>Another Area</li>
        </ul>

    </aside>

</div>"""

        # write to file
        f.write(message)

# close file
f.close()

# open in browser
filename = 'template.html'
webbrowser.open_new_tab(filename)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM