簡體   English   中英

如何使用python打印新行中函數返回的輸出?

[英]how to print the output returned from a function in new lines using python?

我在日志文件中有243607個ips。 函數的輸出連續顯示唯一的ips,因此我無法檢查輸出ips是否唯一。 所以我希望每個ip都能在單獨的行中打印。 因為我是python的新手,我無法弄明白。 有什么辦法嗎?

我也想要打印的ips計數

def unique_ips(): 
    f = open('epiclogs.txt','r')
    ips = set(line.split()[0] 
    for line in f:
        if not line.isspace()) 
            ip = line.split()[0] 
            ips.add(ip) 

    return ips

if name__=='__main':
    print unique_ips() 

要求不完整:

  1. 日志文件的格式未知。
  2. 輸出文件的格式(例如排序?)

我的假設

  1. IP地址位於第一列
  2. 輸出格式應為'[count] [ip address]'

測試數據

10.1.10.190 http://example.com/t1 404
10.1.10.171 http://example.com/t1 404

10.1.10.180 http://example.com/t2 200
10.1.10.190 http://example.com/t1 404
10.1.11.180 http://example.com/t3 302

程序

#!/usr/bin/env python
# 
# Counts the IP addresses of a log file.
# 
# Assumption: the IP address is logged in the first column.
# Example line: 10.1.10.190 http://example.com/t1 404
#

import sys

def extract_ip(line):
    '''Extracts the IP address from the line.
       Currently it is assumed, that the IP address is logged in
       the first column and the columns are space separated.'''
    return line.split()[0]

def increase_count(ip_dict, ip_addr):
    '''Increases the count of the IP address.
       If an IP address is not in the given dictionary,
       it is initially created and the count is set to 1.'''
    if ip_addr in ip_dict:
        ip_dict[ip_addr] += 1
    else:
        ip_dict[ip_addr] = 1

def read_ips(infilename):
    '''Read the IP addresses from the file and store (count)
       them in a dictionary - returns the dictionary.'''
    res_dict = {}
    log_file = file(infilename)
    for line in log_file:
        if line.isspace():
            continue
        ip_addr = extract_ip(line)
        increase_count(res_dict, ip_addr)
    return res_dict

def write_ips(outfilename, ip_dict):
    '''Write out the count and the IP addresses.'''
    out_file = file(outfilename, "w")
    for ip_addr, count in ip_dict.iteritems():
        out_file.write("%5d\t%s\n" % (count, ip_addr))
    out_file.close()

def parse_cmd_line_args():
    '''Return the in and out file name.
       If there are more or less than two parameters,
       an error is logged in the program is exited.'''
    if len(sys.argv)!=3:
        print("Usage: %s [infilename] [outfilename]" % sys.argv[0])
        sys.exit(1)
    return sys.argv[1], sys.argv[2]

def main():
    infilename, outfilename = parse_cmd_line_args()
    ip_dict = read_ips(infilename)
    write_ips(outfilename, ip_dict)

if __name__ == "__main__":
    main()

評論

我喜歡小功能 - 每個功能都只做一件事。 恕我直言,這使程序更容易理解。

沒有檢查你的代碼是否有效,但是添加了新的代碼,這可以完成你的任務。

嘗試這個,

def unique_ips(): 
    f = open('epiclogs.txt','r')
    fout = open('uniqueip.txt','w') # Added
    ips = set(line.split()[0] 
    for line in f:
        if not line.isspace()): 
            ip = line.split()[0] 
            ips.add(ip) 
            fout.write("%s\n"%ip) # Added
    f.close() # Added
    fout.flush() # Added
    fout.close() # Added
    return ips

if name__=='__main':
    print unique_ips() 

unique_ips()返回一個set ,這意味着每個IP地址只出現一次。 如果要在文件中逐行查看地址,可以將print unique_ips()行更改為:

if __name__== '__main__':
    f = file('ip_addresses', 'w')
    for ip in unique_ips():
        f.write(ip + '\n')

暫無
暫無

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

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