我有一個Python腳本,它在命令行運行腳本時將命令行參數分配給不同的變量。我之前完成了這個任務,但幾乎沒有任何問題,但是這一次我掛上了似乎有點技術性的問題,而我卻無法輕鬆解決。Python等價運算符不按我期望的方式工作
比方說,我有beginining靠近下列語句:
n_value = sys.argv[3]
我期待的命令行參數是一個整數的字符串,1直通6.然後,後來,我想測試n_value指向的值以決定接下來的路向。所以,我有以下幾點:
if n_value == "1":
(do something)
最後,有一個爲在那裏是沒有預料到的命令行參數的輸入情況的else語句。每次我嘗試運行該程序時,都會收到此信息。我試圖改變if語句說這樣的話:
if n_value == 1:
或者:
if n_value is "1"
等。我已經嘗試了一堆東西,但我似乎無法使該值真正。
我也試過在這些語句前用set_trace()使用pdb。在調試器中,我試着查看錶達式n_value ==「1」的值,並且它表示「True」。這導致我相信這可能是我使用的版本中的一些技術問題(即,我做錯了一些事情,但我沒有意識到),或者我只是不理解Python等價的細節操作。
最後說明:我一直在使用的Python版本是2.6和2.7。據我所知,兩者都有同樣的問題。
如果有興趣,請參閱下面我的main()方法的開頭:
def main():
if len(sys.argv) != 4:
print(r'usage: python(2.6) ./log_likelihood_ngrams.py /path/to/input_file1 /path/to/input_file2 n_value')
sys.exit(1)
# Store command-line arguments as variables
input_file1_path = sys.argv[1]
input_file2_path = sys.argv[2]
n_value = sys.argv[3]
# Tokenize the input files and save their n-grams in n-gram-lists
# For 1-grams
if n_value == '1':
ngrams_list1 = tokenize(input_file1_path)
ngrams_list2 = tokenize(input_file2_path)
# For 2-grams
if n_value == '2':
ngrams_list1 = bigram_list(input_file1_path)
ngrams_list2 = bigram_list(input_file2_path)
# For 3-grams
if n_value == '3':
ngrams_list1 = trigram_list(input_file1_path)
ngrams_list2 = trigram_list(input_file2_path)
# For 4-grams
if n_value == '4':
ngrams_list1 = four_gram_list(input_file1_path)
ngrams_list2 = four_gram_list(input_file2_path)
# For 5-grams
if n_value == '5':
ngrams_list1 = five_gram_list(input_file1_path)
ngrams_list2 = five_gram_list(input_file2_path)
# For 6-grams
if n_value == '6':
ngrams_list1 = six_gram_list(input_file1_path)
ngrams_list2 = six_gram_list(input_file2_path)
# If n is invalid, print an error message and exit the program.
else:
sys.stderr.write('\n\nThe value of n you entered is not valid!\nPlease enter a value between 1 and 6, inclusive.\n')
sys.exit(1)
您是否檢查過您是否嘗試比較不同的編碼? 另外,你有沒有嘗試str(1)? –
打印'repr(nvalue)'。這將揭示答案:-) –
@VikramSaran是的,我有。我嘗試將初始賦值更改爲n_value = str(sys.argv [3])和n_value = sys.argv,然後是n_value = str(n_value)(僅僅因爲我遇到過在類型化實際sys.argv方法之前遇到的問題)。我也嘗試使用int()進行類型轉換,並將值更改爲實際整數,而不是那些整數的字符串。 – user3029690