gpt4 book ai didi

python - 在linux上运行python程序

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:56:33 25 4
gpt4 key购买 nike

我对 linux 和 python 不是很熟悉。我正在上这门课,它有 python 上倒排索引程序的示例代码。我想知道如何运行和测试代码。这是提供给我的代码。

这是映射文件的代码。 (inverted_index_map.py)

import sys
for line in sys.stdin:
#print(line)
key, value = line.split('\t', 1)
for word in value.strip().split():
if len(word) <=5 and len(word) >= 3:
print '%s\t%s' % (word, key.split(':', 1)[0]) #what are we emitting?

这是reduce程序的代码。 (inverted_index_reduce.py)

import sys
key = None
total = ''
for line in sys.stdin:
k, v = line.split('\t', 1)

if key == k:
total += v.strip() #what are we accumulating?
else:
if key:
print '%s\t%s' % (key, total) #what are we printing?
key = k
total = v

if key:
print '%s\t%s' % (key, total) #what are we printing?

这不是一个可执行文件所以我试过了

chmod +x inverted_index_map.py

然后我尝试运行程序:

./inverted_index_map.py testfilename.txt

但我不确定程序是否正在等待来自键盘或其他东西的某种输入。所以我的问题是如何测试这段代码并查看结果?我真的不熟悉python。

最佳答案

这两个程序是作为命令行工具编写的,这意味着它们从标准输入获取输入并将其显示到标准输出。默认情况下,这意味着它们从键盘获取输入并在屏幕上显示输出。在大多数 Linux shell 中,您可以使用 <file.txt 更改输入的来源和输出的去向。从 file.txt 获取输入和 >file.txtfile.txt 中写入输出.此外,您可以使用 firstcommand | secondcommand 使一个命令的输出成为另一个命令的输入。 .

另一个问题是您发布的脚本没有 #! (shebang) 行,这意味着您将需要使用 python inverted_index_map.py运行您的程序。

如果你想运行inverted_index_map.py来自 testfilename.txt 的输入并在屏幕上看到输出,您应该尝试运行:

python inverted_index_map.py <testfilename.txt

运行inverted_index_map.py其次是 inverted_index_reduce.py来自 testfilename.txt 的输入并将输出写入 outputfile.txt ,你应该尝试运行:

python inverted_index_map.py <testfilename.txt | python inverted_index_reduce.py >outputfile.txt

关于python - 在linux上运行python程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37693750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com