[英]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:本质上,有一个文件“Shannon_argv.py”,它看起来像这样:
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.我必须通过在“导入数学”行之后创建一个空列表来修改它,然后在“H = 0”行之后创建一个新列表 P 。
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.还有另一个文件 readfile_countline.py,有人告诉我需要打开并从每一行中取出一个值,然后将其添加到列表 P 中,然后对所有行重复此操作,但我不知道这是什么意思,或者在哪里添加等。我还被告知 L.append(x) 操作会派上用场。
I am using emacs to edit these python scripts in a Linux shell.我正在使用 emacs 在 Linux shell 中编辑这些 python 脚本。 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.要从命令行参数更改您使用的文件,您可以使用
filename = sys.argv[1]
从参数向量中获取文件名。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.