python 中 argv和raw_input()有什么区别?

这篇文章介绍了Python中获取用户输入的两种方式:argv用于从命令行接收参数,而raw_input()则在脚本运行时获取用户输入。通过一个示例脚本展示了如何使用argv解析参数,并解释了解包的概念。当argv参数不足时,会引发ValueError。同时,文章提到Python的适用性和学习Python的好处,包括高薪就业和兼职机会,并提供了Python学习资源。

argv和raw_input()有什么区别?它们的区别在于要求用户输入的位置不同。如果你想让用户在命令行输入你的参数,你应该使用argv .,如果你希望用户在脚本执行的过程中输入参数,那就就要用到raw_input() 。下面我们写一个可以接收参数的脚本,来具体认识一下argv和raw_input()。
在这里插入图片描述

from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third

第一行代码中,我们用到一个 import 语句,这是将Python的功能模块加入你自己脚本的方法。Python 不会一下子将它所有的功能提供给你,而是让你需要什么就调用什么。这样可以让你的程序更加精简,而后面的程序员看到你的代码的时候,这些“import”语句可以作为提示,让他们明白你的代码用到了哪些功能。

argv 就是所谓的“参数变量”,它是一个非常标准的编程术语。在其他的编程语言里你也可以看到它。这个变量包含了你传递给 Python 的参数。

代码的第3行将 argv 进行“解包(unpack)”,与其将所有参数放到同一个变量下面,我们将每个参数赋予一个变量名: script, first, second, 以及 third。这也许看上去有些奇怪,不过”解包”可能是最好的描述方式了。它的含义很简单:“把argv中的东西解包,将所有的参数依次赋予左边的变量名”。

前面使用import让程序实现更多的功能,我们把import称为功能,它们的真正名称其实是模块。像下面的示例一样将你的脚本运行起来:

$ python ex13.py first 2nd 3rd
The script is called: ex13.py
Your first variable is: first
Your second variable is: 2nd
Your third variable is: 3rd

如果你每次输入的参数不一样,那你看到的输出结果也会略有不同:

$ python ex13.py stuff things that
The script is called: ex13.py
Your first variable is: stuff
Your second variable is: things
Your third variable is: that
$$
python ex13.py apple orange grapefruit
The script is called: ex13.py
Your first variable is: apple
Your second variable is: orange
Your third variable is: grapefruit

你可以将 first , 2nd , 和 3rd 替换成任意你喜欢的3个参数。如果你没有运行对,你可能会看到的错误信息:

$ python ex13.py first 2nd
Traceback (most recent call last):
File "ex13.py", line 3, in <module>
script, first, second, third = argv
ValueError: need more than 3 values to unpack

argv和raw_input()的区别就讲到这里了,大家都弄明白了吗?

好了,今天的分享就到这里,接下来给大家来一波福利。Python是一门非常不错的编程语言,薪资待遇高、就业前景好。即使你不想出去上班,也可以利用Python在家做兼职(比如爬取客户需要的数据、量化交易、代写程序等)。

如果你对Python感兴趣,想通过学习Python获取更高的薪资,那下面这套Python学习资料一定对你有用!

😝朋友们如果有需要的话,可以V扫描下方二维码免费领取🆓

学好 Python 不论是就业还是做副业赚钱都不错,但要学会 Python 还是要有一个学习规划。最后大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!

#### **一、Python学习路线**

image-20230619144606466

python学习路线图1

二、Python基础学习
1. 开发工具

2. 学习笔记

在这里插入图片描述

3. 学习视频

在这里插入图片描述

三、Python小白必备手册

图片

四、数据分析全套资源

在这里插入图片描述

五、Python面试集锦
1. 面试资料

在这里插入图片描述

在这里插入图片描述

2. 简历模板

在这里插入图片描述

** 因篇幅有限,仅展示部分资料,添加上方即可获取**
### 使用 `six` 库实现 Python 2 Python 3 的跨版本兼容性 为了确保给定的 Python 2 代码能够在 Python 3 中正常运行并保持向后兼容性,可以使用 `six` 库来处理两个版本之间的差异。以下是详细的解决方案: #### 1. 安装 `six` 库 首先需要安装 `six` 库。可以通过以下命令安装: ```bash pip install six ``` #### 2. 修改代码以支持 Python 2 Python 3 以下是将提供的代码转换为 Python 3 兼容版本的详细修改过程: ##### (1) 替换 `xrange` 为 `six.moves.range` 在 Python 3 中,`xrange` 已被移除,取而代之的是 `range`,它具有与 `xrange` 相同的行为。通过 `six.moves.range` 可以在两个版本中实现兼容性。 ```python from six.moves import range # 替换 xrange 为 six.moves.range[^1] ``` ##### (2) 替换 `print` 语句为函数 Python 2 中的 `print` 是一个语句,而在 Python 3 中是一个函数。通过 `six.print_` 可以实现兼容性。 ```python from six import print_ # 使用 six.print_ 替代原始的 print 语句[^1] print_("Processing input...") ``` ##### (3) 替换字符串方法编码 在 Python 3 中,字符串默认是 Unicode 类型,而 Python 2 中需要显式指定。通过 `six.text_type` `six.binary_type` 可以处理字符串类型的差异。 ```python import six if isinstance(some_string, six.text_type): # 检查是否为 Unicode 字符串 pass ``` ##### (4) 替换 `iteritems` 其他字典方法 在 Python 3 中,`dict.iteritems()` 等方法已被移除,取而代之的是 `items()` 返回迭代器。通过 `six.iteritems` 可以实现兼容性。 ```python from six import iteritems for key, value in iteritems(some_dict): # 替换 iteritems 为 six.iteritems[^1] pass ``` ##### (5) 替换异常捕获语法 在 Python 3 中,异常捕获语法发生了变化,使用 `as` 关键字。通过 `six.reraise` 可以处理异常重新抛出的差异。 ```python import six try: some_code() except SomeException as e: six.reraise(SomeException, e) # 使用 six.reraise 处理异常重新抛出[^1] ``` ##### (6) 替换输入函数Python 3 中,`input()` 始终返回字符串,而 Python 2 中的 `raw_input()` 被移除。通过 `six.input` 可以实现兼容性。 ```python from six.moves import input # 使用 six.moves.input 替代 raw_input user_input = input("Enter something: ") ``` #### 3. 修改后的完整代码示例 以下是经过修改后的完整代码示例,确保其在 Python 2 Python 3 中都能正常运行: ```python from __future__ import division import re import sys import random import numpy as np import os import glob from math import sqrt from collections import Counter from nltk.stem.wordnet import WordNetLemmatizer from nltk.corpus import stopwords from nltk.tokenize import TextTilingTokenizer from six.moves import range, input # 使用 six.moves 替代 xrange raw_input[^1] from six import print_, iteritems, text_type # 使用 six 提供的兼容性工具 lemmatizer = WordNetLemmatizer() stop_words = stopwords.words('english') def tokenize_string(input_str, w): ''' Tokenize a string using the following four steps: 1) Turn all text into lowercase and split into tokens by removing all punctuation except for apostrophes and internal hyphens 2) Remove common words that don't provide much information about the content of the text, called "stop words" 3) Reduce each token to its morphological root (e.g. "dancing" -> "dance") using nltk's lemmatize function. 4) Group the lemmatized tokens into groups of size w, which represents the pseudo-sentence size. Args : input_str : A string to tokenize w: pseudo-sentence size Returns: A tuple (token_sequences, unique_tokens, paragraph_breaks), where: token_sequences: A list of token sequences, each w tokens long. unique_tokens: A set of all unique words used in the text. paragraph_breaks: A list of indices such that paragraph breaks occur immediately after each index. Raises : None ''' paragraphs = [s.strip() for s in input_str.splitlines()] paragraphs = [s for s in paragraphs if s != ""] tokens = [] paragraph_breaks = [] token_count = 0 pat = r"((?:[a-z]+(?:[-'][a-z]+)*))" for paragraph in paragraphs: pgrph_tokens = re.findall(pat, paragraph) tokens.extend(pgrph_tokens) token_count += len(pgrph_tokens) paragraph_breaks.append(token_count) paragraph_breaks = paragraph_breaks[:-1] token_sequences = [] index = 0 cnt = Counter() # split tokens into groups of size w for i in range(len(tokens)): # 使用 six.moves.range 替代 xrange[^1] cnt[tokens[i]] += 1 index += 1 if index % w == 0: token_sequences.append(cnt) cnt = Counter() index = 0 # remove stop words from each sequence for i in range(len(token_sequences)): # 使用 six.moves.range 替代 xrange[^1] token_sequences[i] = [lemmatizer.lemmatize(word) for word in token_sequences[i] if word not in stop_words] # lemmatize the words in each sequence for i in range(len(token_sequences)): # 使用 six.moves.range 替代 xrange[^1] token_sequences[i] = [lemmatizer.lemmatize(word) for word in token_sequences[i]] # get unique tokens unique_tokens = [word for word in set(tokens) if word not in stop_words] return (token_sequences, unique_tokens, paragraph_breaks) # 其他函数类似处理,略去... def main(argv): ''' Tokenize a file and compute gap scores using the algorithm described in Hearst's TextTiling paper. Options to vary w and k. Args : argv[1] : The name of the file where output should be written Returns: None Raises : None ''' if (len(argv) != 2): print_("Usage: python texttiling.py <outfile>") # 使用 six.print_ 替代 print[^1] sys.exit(0) # constants for pseudo-sentence size and block size, respectively. w_start = 20 w_end = 20 k_start = 10 k_end = 10 increment = 2 # empty the file with open(argv[1], "w"): pass # run texttiling for different values of w and k. for w in range(w_start, w_end+1, increment): # 使用 six.moves.range 替代 xrange[^1] for k in range(k_start, k_end+1, increment): # 使用 six.moves.range 替代 xrange[^1] print_("w = {}, k = {}".format(w, k)) # 使用 six.print_ 替代 print[^1] run_tests(argv[1], w, k) if __name__ == "__main__": main(sys.argv) ``` ####
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值