从Python获取.txt文件中的数据

时间:2016-11-25 12:01:53

标签: python python-2.7

Total number of EVENTS in BOX(planner + ondemand) :  54
EVENT # :1

actualEndTime= '20161121T11:34:00' allowCopyToPlanner= 'True' audioType= '2' audioTypeName= 'Simple stereo' baseType= '3' baseTypeName= 'Download' bookedAsOPPV= 'False' bookingActive= '1' bookingDeletedTime= 'None' bookingDiskQuotaName= 'user' bookingExpirationTime= '19700101T01:00:00' bookingKeep= 'False' bookingLock= 'False' bookingSource= '1' bookingTime= '20161121T11:27:00' bookingType= '4' bookingTypeName= 'Download' boxSetLocator= 'hecid://FFC6AE9C' boxSetName= 'Lost S1' boxSetNameSort= 'Lost S1' boxSetRating= '0' canonicalName= 'Lost' cgmsa= '0' channelID= 'None' channelIDType= 'None' channelName= 'abc studios' channelNr= '102' class= 'object.item.videoItem' cmdcMemberNumber= '1' description= 'A plane crash leaves survivors stranded on a jungle island. Contains violence.(S1, ep 1)' episodeNumber= '1' episodeTitle= 'Pilot (part 1 Of 2) Premiere' estimatedBitRate= '5767168' expireFromPlanner= 'False' extensionStartDur= '0' flagsAllowanalogtaping= 'True' flagsCopyprotected= 'False' flagsCurrentseries= 'False' flagsHasaudiodesc= 'False' flagsHasforeignsubtitles= 'False' flagsHd= 'False' flagsIppv= 'False' flagsIs3D= 'False' flagsIsadult= 'False' flagsIslinked= 'False' flagsOppv= 'False' flagsWidescreen= 'True' genre= '3' genreExtended= '3,772' genreId= 'nds.com_internal' genreName= 'Entertainment' groupID= '0' guardEndDur= 'None' guardStartDur= 'None' isBTO= 'False' isPdlTrailer= '0' isPlaying= 'False' isSeriesLinked= 'False' isShowLinked= '0' isSplitEvent= 'False' isViewed= 'False' itemId= 'BOOK:688045263' itemParentid= '3' itemRestricted= '0' lastPlaybackPosition= '0' lastViewedTime= '19700101T01:00:00' marketingMsg= 'None' oigProgId= '4291238560' parentServiceLocator= 'None' parentalRatingScheme= '1' pdlDownloadStatus= '5' pdlDownloadStatusName= 'ended' pdlPlaybackAvailable= 'True' pdlQueuePosition= '0' pinRating= '4' pinRatingScheme= '1' programID= 'oig://FFC71AA0' programIDType= 'nds.com_URI' purchaseType= '0' pushExpiryEnd= 'None' pushExpiryStart= 'None' pushHasValidTrailer= 'True' pushLocator= 'None' pushPublishTime= 'None' rating= '0' ratingName= 'Unrated' ratingType= 'nds.com_internal' recStatus= '0' recStatusContentstatus= '3' recStatusContentstatusName= 'All' recStatusException= '100' recStatusFailed= 'False' recStatusName= 'Not applicable' recStatusRecstate= '0' recordedDuration= 'P0D00:40:39' recordedStartDateTime= '20161121T11:27:50' recordingID= 'oig://FFC71AA0' reminderStatus= '1' reminderStatusIsvcrtimer= 'False' reminderStatusName= 'event is scheduled for a reminder' remoteCDSItemID= 'None' res= 'file://pvr/2902BCCF' resDuration= '0:40:39' resProtocolinfo= 'internal:10.10.8.89:*:*' resSize= '660887492.0' scheduledDuration= 'P0D00:40:39' scheduledEndTime= 'None' scheduledStartTime= 'None' seasonNumber= '1' seriesID= 'None' seriesInfo= '1/1' serviceType= '0' serviceTypeName= 'Undefined' srsRecordTaskID= 'RT:2902BCCF' subGroupID= '0' title= 'Lost' totalChildSize= '0.0'

EVENT # :2
actualEndTime= '20161121T11:41:00' allowCopyToPlanner= 'True' audioType= '2' audioTypeName= 'Simple stereo' baseType= '3' baseTypeName= 'Download' bookedAsOPPV= 'False' bookingActive= '1' bookingDeletedTime= 'None' bookingDiskQuotaName= 'user' bookingExpirationTime= '19700101T01:00:00' bookingKeep= 'False' bookingLock= 'False' bookingSource= '1' bookingTime= '20161121T11:27:00' bookingType= '4' bookingTypeName= 'Download' boxSetLocator= 'hecid://FFC6AE9C' boxSetName= 'Lost S1' boxSetNameSort= 'Lost S1' boxSetRating= '0' canonicalName= 'Lost' cgmsa= '0' channelID= 'None' channelIDType= 'None' channelName= 'abc studios' channelNr= '0' class= 'object.item.videoItem' cmdcMemberNumber= '2' description= 'Jack tends to a wounded man who reveals a secret about Kate. Contains strong language, violence.(S1, ep 2)' episodeNumber= '2' episodeTitle= 'Pilot (part 2 Of 2) Premiere' estimatedBitRate= '5767168' expireFromPlanner= 'False' extensionStartDur= '0' flagsAllowanalogtaping= 'True' flagsCopyprotected= 'False' flagsCurrentseries= 'False' flagsHasaudiodesc= 'False' flagsHasforeignsubtitles= 'False' flagsHd= 'False' flagsIppv= 'False' flagsIs3D= 'False' flagsIsadult= 'False' flagsIslinked= 'False' flagsOppv= 'False' flagsWidescreen= 'True' genre= '3' genreExtended= '3,772' genreId= 'nds.com_internal' genreName= 'Entertainment' groupID= '0' guardEndDur= 'None' guardStartDur= 'None' isBTO= 'False' isPdlTrailer= '0' isPlaying= 'False' isSeriesLinked= 'False' isShowLinked= '0' isSplitEvent= 'False' isViewed= 'False' itemId= 'BOOK:688045265' itemParentid= '3' itemRestricted= '0' lastPlaybackPosition= '0' lastViewedTime= '19700101T01:00:00' marketingMsg= 'None' oigProgId= '4291228354' parentServiceLocator= 'None' parentalRatingScheme= '1' pdlDownloadStatus= '5' pdlDownloadStatusName= 'ended' pdlPlaybackAvailable= 'True' pdlQueuePosition= '0' pinRating= '4' pinRatingScheme= '1' programID= 'oig://FFC6F2C2' programIDType= 'nds.com_URI' purchaseType= '0' pushExpiryEnd= 'None' pushExpiryStart= 'None' pushHasValidTrailer= 'True' pushLocator= 'None' pushPublishTime= 'None' rating= '0' ratingName= 'Unrated' ratingType= 'nds.com_internal' recStatus= '0' recStatusContentstatus= '3' recStatusContentstatusName= 'All' recStatusException= '100' recStatusFailed= 'False' recStatusName= 'Not applicable' recStatusRecstate= '0' recordedDuration= 'P0D00:38:48' recordedStartDateTime= '20161121T11:35:03' recordingID= 'oig://FFC6F2C2' reminderStatus= '1' reminderStatusIsvcrtimer= 'False' reminderStatusName= 'event is scheduled for a reminder' remoteCDSItemID= 'None' res= 'file://pvr/2902BCD1' resDuration= '0:38:48' resProtocolinfo= 'internal:10.10.8.89:*:*' resSize= '631299676.0' scheduledDuration= 'P0D00:38:48' scheduledEndTime= 'None' scheduledStartTime= 'None' seasonNumber= '1' seriesID= 'None' seriesInfo= '1/2' serviceType= '0' serviceTypeName= 'Undefined' srsRecordTaskID= 'RT:2902BCD1' subGroupID= '0' title= 'Lost' totalChildSize= '0.0'

我有一个output.txt文件。当用户输入频道号码时,我想删除整个事件。

例如,如果用户输入ChannelNr=102,那么我是否可以抓取'BOOK:688045263' 数字我将能够删除与channelNr相关的事件。

我可以在具有以下功能的文件中获取channelNr。

def check_channel_number(self):

        print "***************Channel Checker *********************" 

        user_channel_number = int(re.sub('\D', '', raw_input("Enter a channel number, (3digit): "))[:3]);

        self.user_channel_number = user_channel_number

        channel = ("channelNr= '%d'") % (user_channel_number)

        # channel_search = channel + str(user_channel_number)

        datafile = file('output.txt')

        found = False

        for line in datafile:

            if channel in line:
                found = True 
                return user_channel_number

        print 'The channel number you entered is not on the planner'

        return False

所以,我的问题是如何在相关的ChannelNr上获得图书编号(itemId ='BOOK:688045263)?

2 个答案:

答案 0 :(得分:0)

谷歌的第一个结果是https://www.tutorialspoint.com/python/string_find.htm,它有一些很好的资源。

例如,

string.find()将为您提供索引。

str1 = "this is string example....wow!!!";
str2 = "exam";

print str1.find(str2)
15

但这不是正则表达式。它 - 是 - 是正则表达式吗?

你能把它导出到JSON吗?这将是一个非常,更清洁的解决方案,将为您节省大量的头痛。

您将此文本输出为

channel = ("channelNr= '%d'") % (user_channel_number)

你可以尝试

>>> import json
>>> print json.dumps({'channelNr': user_channel_number}, separators=(',', ': '))

会给你

{
"channelNr": 602 
}

现在您可以使用

获取数据
jsonData = {    "channelNr": 602     }
dictionary = json.loads(jsonData)[0]
channelNr = dictionary['channelNr']

并搜索

return(channelNr  == 602)
True

答案 1 :(得分:0)

我已经获得了channelNr。我的问题是我如何获得BOOK ID,因此我可以删除事件。

事件将在output.txt文件中导出。

 def check_channel_number(self):

    print "***************Channel Checker *********************" 

    user_channel_number = int(re.sub('\D', '', raw_input("Enter a channel number, (3digit): "))[:3]);

    self.user_channel_number = user_channel_number

    channel = ("channelNr= '%d'") % (user_channel_number)


    # book = ("BOOK: '%d") % ()

    datafile = file('output.txt')

    found = False

    for line in datafile:

        if channel in line:
            found = True 
            return user_channel_number

        print 'The channel number you entered is not on the planner'
        break        



def delete_events(self):


    self.ucn = self.user_channel_number

    are_you_sure = raw_input('Channel number is correct. Are you sure to delete channel number? (y/n): ') 

    if are_you_sure == 'y' and self.ucn >0 :

        print 'The selected program will be deleted'

        action = 'DeleteEvent'
        menu_action = 'all'
        book = 'BOOK:688045265'
        arg_list = [('C:\\Users\\yke01\\Documents\\StormTest\\Scripts\\Completed'
                        '\\Utils\\UPNP_Client_Cmd_Line.py')]
        arg_list.append(' --action=')
        arg_list.append(action)
        arg_list.append(' --ip=')
        arg_list.append('10.10.8.89')
        arg_list.append(' --objectId=')
        arg_list.append(book)

        subprocess.call(["python", arg_list])

        print 'The program deleted successfully'
    else: 
        print 'The program is NOT deleted!'

正如您所看到的,book变量在delete_events()函数中是硬编码的。我试图找到一种方法来动态传递书籍ID(9位数)。