通过使用python将一个文件与另一个文件匹配来打印该文件的内容和索引位置

2024-09-24 12:33:56 发布

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

我对python不熟悉 我想要的是能够打印一个文件的内容,我有这样的。。你知道吗

Mashed Potatoes , topped with this and that ...................... 9.99$

同样地

Product_name , description ......................... price

当我将它与只包含产品名称的文件匹配时

Mashed Potatoes

Past

Caesar Salad

etc. etc.

第一个文件的内容顺序不统一 所以我尝试用搜索匹配打印的方法

我希望你能理解我的问题

这就是我尝试过的

     import re

      content_file = open('/Users/ashishyadav/Downloads/pdfminer-20110515/samples/te.txt',"r")
      product_list = open('/Users/ashishyadav/Desktop/AQ/te.txt',"r")
      output = open("output.txt" , "w")
      line = content_file.read().lower().strip()
      for prod in product_list:
        for match in re.finditer(prod.lower().strip(), line):
         s=match.start()
         e=match.end()
         print >>output, match.group(),"\t",
         print >>output, '%d:%d' % ( s, e),"\n",

我的代码所做的是将第二个产品列表文件与完整内容文件匹配,但只给出产品名称的索引,而不是描述和价格。。你知道吗

我想要的是从产品名称到价格的索引/span。。你知道吗

比如土豆泥——9.99美元(土豆泥-[0:58]),我刚拿到[0:14]

以及任何方式打印的说明和价格使用相同的方法

提前谢谢


Tags: 文件方法retxt内容outputmatchetc
1条回答
网友
1楼 · 发布于 2024-09-24 12:33:56
  • 将整个“第二个文件”读入一个集合X
  • 逐行读取“第一个”文件。你知道吗
  • 对于每行,提取逗号前的部分。你知道吗
  • 如果该零件在集合X中,则打印所需内容。你知道吗

如果你需要python中的这个,请告诉我。你知道吗

# Read the whole "second file" into a set X.
with open('foo') as fp:
    names = set(fp)

# Read the "first" file line by line.
with open('bar') as fp:
    for line in fp:

        # For each line, extract the part before the comma.
        name = line.split(',')[0]

        # If this part is in the set X, print whatever is desired.
        if name in names:
             print line

相关问题 更多 >