我正在寻找打印“蠕虫”从一套只有一次。有办法吗?

2024-05-29 02:56:33 发布

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

这是到目前为止我的脚本,我们有一个文件要打开和排序。当我打印结果时,它会打印蠕虫的名称,就像每个蠕虫打印10-12次一样。有没有办法让它们只显示一次?如果您能提供任何帮助,我将不胜感激

from __future__ import print_function
'''

Week Two Assignment 1 - File Processing
'''

'''
Complete the script below to do the following:
1) Add your name, date, assignment number to the top of this script
2) Open the file redhat.txt 
   a) Iterate through each line of the file
   b) Split eachline into individual fields (hint str.split() method)
   c) Examine each field of the resulting field list
   d) If the word "worm" appears in the field then add the worm name to the set of worms
   e) Once you have processed all the lines in the file
      sort the set 
      iterate through the set of worm names
      print each unqiue worm name 
3) Submit
   NamingConvention: lastNameFirstInitial_Assignment_.ext
   for example:  hosmerC_WK2-1_script.py
                 hosmerC_WK2-2_screenshot.jpg
   A) Screenshot of the results in WingIDE
   B) Your Script
'''
import os

SCRIPT_NAME    = "Week Two Assignment 1 - File Processing"
SCRIPT_VERSION = "Version 1.0"
SCRIPT_AUTHOR  = "Author: Brandon Holman"
SCRIPT_DATE = "January 20 2021"

print()
print(SCRIPT_NAME)
print(SCRIPT_VERSION)
print(SCRIPT_AUTHOR)
print(SCRIPT_DATE)
print()


uniqueWorms = set()

with open("redhat.txt", 'r') as logFile:
    for eachLine in logFile:
        ''' your code starts here '''
        
       line = eachLine.split():

       for field in line:
           if 'Worm' in field:
               uniqueWorms.add(field)
       for worms in sorted(uniqueWorms):
           print(worms)
     
                
        print("Script Complete")
    

Tags: ofthetonameinfieldforscript
1条回答
网友
1楼 · 发布于 2024-05-29 02:56:33

仅当您处理完文件后才处理蠕虫列表

for eachLine in logFile:
    
    print(eachLine)
     
    fields = eachLine.split()
    for field in fields:
        if field.lower().find('worm')!= -1:
            uniqueWorms.append(field.lower())

# You're all done reading the file and collecting worms.
# NOW you can print the results
uniqueWorms = sorted(uniqueWorms)
for worm in uniqueWorms:
    print(worm)

相关问题 更多 >

    热门问题