【发布时间】:2017-06-30 21:44:24
【问题描述】:
我有一个定义多个函数的文档(assignment_2a.py)。我正在努力实现以下目标:
Modify the [assignment_2a.py](../code/assignment_2a.py) to be able to run
the program `make_random_story` from the command line:
```
$ python assignment_2a.py '../data/alice.txt' 2 200
```
我知道如何通过进入 ipython 来运行这个指定的函数,它运行良好。但是如何更改文档以便我可以使用上述命令从命令行运行它,即以该格式指定输入变量?
更新:我按照 cmets 中的建议更新了函数,并收到以下错误消息:
COMMAND LINE INPUT:
python assignment_2a.py '../data/alice.txt' 2 200
COMMAND LINE OUTPUT:
Traceback (most recent call last):
File "assignment_2a.py", line 202, in <module>
make_random_story(*sys.argv[1:])
File "assignment_2a.py", line 189, in make_random_story
for i in xrange(0,num_words):
TypeError: an integer is required
以下是相关的更新函数文本:
def make_random_story(f, n_gram=2, num_words=200):
f = open(f)
random.seed('Is the looking-glass is half full or half-empty?')
story = ''
if n_gram==1:
d = associated_unigrams(f)
elif n_gram==2:
d = associated_bigrams(f)
elif n_gram==3:
d = associated_trigrams(f)
for i in xrange(0,num_words):
chosenkey = random.choice(d.keys())
story += random.choice(d[chosenkey]) + " "
print story
f.close()
if __name__ == '__main__':
make_random_story(*sys.argv[1:])
【问题讨论】:
-
请发minimal reproducible example。尝试将
sys.argv打印为列表...您注意到了什么? -
考虑接受这个问题的答案:stackoverflow.com/questions/44729412/…
标签: python