从一个文件写入另一个python

2024-09-30 19:27:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图采取一些信息,我从一个网页和写的变量之一到一个文件,但我没有运气,这可能是非常容易,但我迷路了。下面是其中一行的示例,共有1253行。你知道吗

<div class='entry qual-5 used-demoman slot-head bestprice custom' data-price='3280000' data-name="Kill-a-Watt Allbrero" data-quality="5" data-australium="normal" data-class="demoman" data-particle_effect="56" data-paint="" data-slot="cosmetic" data-consignment="consignment">

我在名为data name的字段后面,它不在每行的同一位置。我试过了,但没用

mfile=open('itemlist.txt','r')
mfile2=open('output.txt','a')
for row in mfile:
    if char =='data-name':
        mfile2.write(char)

编辑1:

我做了一个“你好,嗨,花生”的示例文件 如果有:

for row in mfile:
    print row.index('hello')

它会像预期的那样打印0,但是当我把hello改成hi时,它没有返回1,它什么也没有返回。你知道吗


Tags: 文件nameintxt示例fordataopen
2条回答

让我们尝试使用常见的字符串操作方法来查找值:

>>> line = '''<div class='entry qual-5 used-demoman slot-head bestprice custom' data-price='3280000' data-name="Kill-a-Watt Allbrero" data-quality="5" data-australium="normal" data-class="demoman" data-particle_effect="56" data-paint="" data-slot="cosmetic" data-consignment="consignment">'''

我们可以使用^{}来查找字符串在字符串中的位置:

>>> line.index('data-name')
87

现在我们知道我们需要开始为我们感兴趣的属性寻找索引87

>>> line[87:]
'data-name="Kill-a-Watt Allbrero" data-quality="5" data-australium="normal" data-class="demoman" data-particle_effect="56" data-paint="" data-slot="cosmetic" data-consignment="consignment">'

现在,我们也需要删除data-name="部分:

>>> start = line.index('data-name') + len('data-name="')
>>> start
98
>>> line[start:]
'Kill-a-Watt Allbrero" data-quality="5" data-australium="normal" data-class="demoman" data-particle_effect="56" data-paint="" data-slot="cosmetic" data-consignment="consignment">'

现在,我们只需要找到右引号的索引,然后我们就可以提取属性值:

>>> end = line.index('"', start)
>>> end
118
>>> line[start:end]
'Kill-a-Watt Allbrero'

然后我们有了我们的解决方案:

start = line.index('data-name') + len('data-name="')
end = line.index('"', start)
print(line[start:end])

我们可以把它放在循环中:

with open('itemlist.txt','r') as mfile, open('output.txt','a') as mfile2w
    for line in mfile:
        start = line.index('data-name') + len('data-name="')
        end = line.index('"', start)
        mfile2.write(line[start:end])
        mfile2.write('\n')

也可以使用beautifulsoup

a.html

<html>
    <head>
        <title> Asdf </title>
    </head>
    <body>

        <div class='entry qual-5 used-demoman slot-head bestprice custom' data-price='3280000' data-name="Kill-a-Watt Allbrero" data-quality="5" data-australium="normal" data-class="demoman" data-particle_effect="56" data-paint="" data-slot="cosmetic" data-consignment="consignment">

    </body>
</html>

a.py

from bs4 import BeautifulSoup
with open('a.html') as f:
    lines = f.readlines()
soup = BeautifulSoup(''.join(lines), 'html.parser')
result = soup.findAll('div')[0]['data-price']
print result
# prints 3280000

我的观点是,如果您的任务像您的示例中那样简单,那么实际上没有必要使用beautifulsoup。但是,如果它更复杂,或者它会更复杂。考虑用beautifulsoup试试。你知道吗

相关问题 更多 >