簡體   English   中英

如何搜索文本文件的文件夾以查看是否存在特定字符串,然后使用Python提取兩個單詞之間的字符串?

[英]How to search a folder of text files to see if a specific string exists and then extract a string between two words using Python?

目前,我只是想弄清楚為什么此代碼無法正常工作。

編輯:編寫了一些新代碼

編輯2:已解決(通讀注釋提醒我對with.open()進行編碼,所以現在看起來像這樣,

編輯3:我需要兩個單詞之間拉“字符串”(日期)的新代碼。

import os
items=os.listdir("C:/output")


for names in items:
  if names.endswith(".txt"):
    with open('C:/output/' + names, encoding="utf8") as currentFile:
      text = currentFile.read()
      if ('Date Released' in text):
           a = 'Released'
           b = 'Description'
           startpos = text.find(a) + len(a)
           endpos = text.find(b, startpos)
           print('Date Released ' + text[startpos:endpos] + names + '\n')
           #print ('Found in ' + names[:-4] + '\n')
      else:
          print ('Not in ' + names[:-4] + '\n')

我現在得到輸出:

Date Released :  12/14/2016



1393-004IP_ B_ C2  filename

Date Released :  4/11/2017



1476-002 IP, filename

Date Released :  9/25/2015



1987-XXX IP filename

有沒有辦法將發布日期:#/ ## / ####行與文件名放在同一行? 另外,我現在運行此命令時得到的一些輸出是垃圾。 我假設這可能是因為檢查了多次發布日期或if條件的可能缺陷?

如果您使用的是Windows,請嘗試在路徑名中使用雙“ \\”而不是單“ /”

暫無
暫無

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

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