简体   繁体   中英

How do I modify a python script to use an external file as the input in the command line?

I am very new to coding so excuse any jargon errors in my questions. I'm wondering how to modify a script so that when I type the command line with different file names, it returns different calculations. Here is the expected outcome if I do the assignment correctly:

% chmod a+x argv.py
% python Shannon_readfile.py populationA.txt
24.0
1.51309299164
% python Shannon_readfile.py populationB.txt 
24.0
0.681610269053

Essentially, there is the file "Shannon_argv.py", which looks like this:

import sys
import math
N=0
H=0

#Calculate N
for i in P:
     a=float(i)
     N=N+a
print(N)

#Calculate H
for i in P:
     a=float(i)
     pa=(a/N)*math.log(a/N)
     H=H+pa
print(-H)

and I have to modify it to by creating an empty list right after the "import math" line, and then by creating a new list P after the "H=0" line.

There is another file, readfile_countline.py, that I was told I need to open and take a value from each line, and add it to the list P, and repeat that for all lines, but I do not know what this means, or where to add, etc. I was also told the L.append(x) manipulation would come in handy.

I am using emacs to edit these python scripts in a Linux shell. I would really appreciate any help/direction I can get asap. Thank you!

To change which file you use from the command line parameters, you can use filename = sys.argv[1] to get the filename from the argument vector. After that, you can open the file, read its contents, and do the processing you need. Assuming from context that your text files contains a single numerical value per line, you could try something like the following:

# Standard library imports.
import math
import sys

# Gets the filename from the command line arguments.
filename = sys.argv[1]

# Reads the data file.
with open(filename, "r") as file:

    P = file.readlines()

# Initializes N and H.
N = 0
H = 0

# Calculates N and H.
for i in P:

    a = float(i)

    N += a
    H += (a / N) * math.log(a / N)

# Prints the results.
print(N)
print(-H)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM