导航:首页 > 编程语言 > 简单的python脚本实例

简单的python脚本实例

发布时间:2022-04-22 03:46:42

python 简单脚本 初学者请大家帮忙

f=open('file_name.txt','r')
txtList=f.readlines()
f2=open('other_file.txt','w')
for data in txtList:
if not data.endswith('OK'):
f2.write(data)
f2.close()
f.close()

② python简单的函数定义和用法实例

python简单的函数定义和用法实例
这篇文章主要介绍了python简单的函数定义和用法,实例分析了Python自定义函数及其使用方法,具有一定参考借鉴价值,需要的朋友可以参考下
具体分析如下:
这里定义了一个温度转换的函数及其用法。
def convertTemp(temp, scale):
if scale == "c":
return (temp - 32.0) * (5.0/9.0)
elif scale == "f":
return temp * 9.0/5.0 + 32
temp = int(input("Enter a temperature: "))
scale = input("Enter the scale to convert to: ")
converted = convertTemp(temp, scale)
print("The converted temp is: " + str(converted))

希望本文所述对大家的Python程序设计有所帮助。

③ 使用Python实现命令行闹钟脚本实例有哪些

importsys
importstring
fromtimeimportsleep

sa=sys.argv
lsa=len(sys.argv)
iflsa!=2:
print"Usage:[python]alarm_clock.pyration_in_minutes"
print"Example:[python]alarm_clock.py10"
print"."
print"."
print"PressCtrl-."
sys.exit(1)

try:
minutes=int(sa[1])
exceptValueError:
print"Invalidnumericvalue(%s)forminutes"%sa[1]
print"Shouldbeaninteger>=0"
sys.exit(1)

ifminutes<0:
print"Invalidvalueforminutes,shouldbe>=0"
sys.exit(1)

seconds=minutes*60

ifminutes==1:
unit_word="minute"
else:
unit_word="minutes"

try:
ifminutes>0:
print"Sleepingfor"+str(minutes)+unit_word
sleep(seconds)
print"Wakeup"
foriinrange(5):
printchr(7),
sleep(1)
exceptKeyboardInterrupt:
print"Interruptedbyuser"
sys.exit(1)

④ python有哪些脚本

Python常用的30个脚本:

1、冒泡排序

2、计算x的n次方的方法

3、计算a*a + b*b + c*c + ……

4、计算阶乘 n!

5、列出当前目录下的所有文件和目录名

6、把一个list中所有的字符串变成小写:

7、输出某个路径下的所有文件和文件夹的路径

8、输出某个路径及其子目录下的所有文件路径


9、输出某个路径及其子目录下所有以.html为后缀的文件

10、把原字典的键值对颠倒并生产新的字典

相关推荐:《Python教程》

11、打印九九乘法表

通过指定end参数的值,可以取消在末尾输出回车符,实现不换行。

12、替换列表中所有的3为3a

13、打印每个名字

** 善于使用 rang() ,会使问题变得简单

14、合并去重

15、随机生成验证码的两种方式

16、计算平方根

17、判断字符串是否只由数字组成

18、判断奇偶数

19、判断闰年

20、获取最大值

21、斐波那契数列

斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13;特别指出:第0项是0,第1项是第一个1。从第三项开始,每一项都等于前两项之和。

22、十进制转二进制、八进制、十六进制

23、最大公约数

23、最小公倍数

24、简单计算器

25、生成日历

26、文件IO

27、字符串判断

28、字符串大小写转换

29、计算每个月天数

30、获取昨天的日期

⑤ Python 如何写脚本

以Python2.7操作为例:

1、首先需要打开电脑桌面,按开始的快捷键,点击Python2.7如图所示的选项进入。

⑥ 如何使用Python为Hadoop编写一个简单的MapRece程序

在这个实例中,我将会向大家介绍如何使用Python 为 Hadoop编写一个简单的MapRece
程序。
尽管Hadoop 框架是使用Java编写的但是我们仍然需要使用像C++、Python等语言来实现Hadoop程序。尽管Hadoop官方网站给的示例程序是使用Jython编写并打包成Jar文件,这样显然造成了不便,其实,不一定非要这样来实现,我们可以使用Python与Hadoop 关联进行编程,看看位于/src/examples/python/WordCount.py 的例子,你将了解到我在说什么。

我们想要做什么?

我们将编写一个简单的 MapRece 程序,使用的是C-Python,而不是Jython编写后打包成jar包的程序。
我们的这个例子将模仿 WordCount 并使用Python来实现,例子通过读取文本文件来统计出单词的出现次数。结果也以文本形式输出,每一行包含一个单词和单词出现的次数,两者中间使用制表符来想间隔。

先决条件

编写这个程序之前,你学要架设好Hadoop 集群,这样才能不会在后期工作抓瞎。如果你没有架设好,那么在后面有个简明教程来教你在Ubuntu linux 上搭建(同样适用于其他发行版linux、unix)

如何使用Hadoop Distributed File System (HDFS)在Ubuntu Linux 建立单节点的 Hadoop 集群

如何使用Hadoop Distributed File System (HDFS)在Ubuntu Linux 建立多节点的 Hadoop 集群

Python的MapRece代码

使用Python编写MapRece代码的技巧就在于我们使用了 HadoopStreaming 来帮助我们在Map 和 Rece间传递数据通过STDIN (标准输入)和STDOUT (标准输出).我们仅仅使用Python的sys.stdin来输入数据,使用sys.stdout输出数据,这样做是因为HadoopStreaming会帮我们办好其他事。这是真的,别不相信!

Map: mapper.py

将下列的代码保存在/home/hadoop/mapper.py中,他将从STDIN读取数据并将单词成行分隔开,生成一个列表映射单词与发生次数的关系:
注意:要确保这个脚本有足够权限(chmod +x /home/hadoop/mapper.py)。

#!/usr/bin/env python

import sys

# input comes from STDIN (standard input)
for line in sys.stdin:
# remove leading and trailing whitespace
line = line.strip()
# split the line into words
words = line.split()
# increase counters
for word in words:
# write the results to STDOUT (standard output);
# what we output here will be the input for the
# Rece step, i.e. the input for recer.py
#
# tab-delimited; the trivial word count is 1
print '%s\\t%s' % (word, 1)在这个脚本中,并不计算出单词出现的总数,它将输出 "<word> 1" 迅速地,尽管<word>可能会在输入中出现多次,计算是留给后来的Rece步骤(或叫做程序)来实现。当然你可以改变下编码风格,完全尊重你的习惯。

Rece: recer.py

将代码存储在/home/hadoop/recer.py 中,这个脚本的作用是从mapper.py 的STDIN中读取结果,然后计算每个单词出现次数的总和,并输出结果到STDOUT。
同样,要注意脚本权限:chmod +x /home/hadoop/recer.py

#!/usr/bin/env python

from operator import itemgetter
import sys

# maps words to their counts
word2count = {}

# input comes from STDIN
for line in sys.stdin:
# remove leading and trailing whitespace
line = line.strip()

# parse the input we got from mapper.py
word, count = line.split('\\t', 1)
# convert count (currently a string) to int
try:
count = int(count)
word2count[word] = word2count.get(word, 0) + count
except ValueError:
# count was not a number, so silently
# ignore/discard this line
pass

# sort the words lexigraphically;
#
# this step is NOT required, we just do it so that our
# final output will look more like the official Hadoop
# word count examples
sorted_word2count = sorted(word2count.items(), key=itemgetter(0))

# write the results to STDOUT (standard output)
for word, count in sorted_word2count:
print '%s\\t%s'% (word, count)
测试你的代码(cat data | map | sort | rece)

我建议你在运行MapRece job测试前尝试手工测试你的mapper.py 和 recer.py脚本,以免得不到任何返回结果
这里有一些建议,关于如何测试你的Map和Rece的功能:
——————————————————————————————————————————————
\r\n
# very basic test
hadoop@ubuntu:~$ echo "foo foo quux labs foo bar quux" | /home/hadoop/mapper.py
foo 1
foo 1
quux 1
labs 1
foo 1
bar 1
——————————————————————————————————————————————
hadoop@ubuntu:~$ echo "foo foo quux labs foo bar quux" | /home/hadoop/mapper.py | sort | /home/hadoop/recer.py
bar 1
foo 3
labs 1
——————————————————————————————————————————————

# using one of the ebooks as example input
# (see below on where to get the ebooks)
hadoop@ubuntu:~$ cat /tmp/gutenberg/20417-8.txt | /home/hadoop/mapper.py
The 1
Project 1
Gutenberg 1
EBook 1
of 1
[...]
(you get the idea)

quux 2

quux 1

——————————————————————————————————————————————

在Hadoop平台上运行Python脚本

为了这个例子,我们将需要三种电子书:

The Outline of Science, Vol. 1 (of 4) by J. Arthur Thomson\r\n
The Notebooks of Leonardo Da Vinci\r\n
Ulysses by James Joyce
下载他们,并使用us-ascii编码存储 解压后的文件,保存在临时目录,比如/tmp/gutenberg.

hadoop@ubuntu:~$ ls -l /tmp/gutenberg/
total 3592
-rw-r--r-- 1 hadoop hadoop 674425 2007-01-22 12:56 20417-8.txt
-rw-r--r-- 1 hadoop hadoop 1423808 2006-08-03 16:36 7ldvc10.txt
-rw-r--r-- 1 hadoop hadoop 1561677 2004-11-26 09:48 ulyss12.txt
hadoop@ubuntu:~$

复制本地数据到HDFS

在我们运行MapRece job 前,我们需要将本地的文件复制到HDFS中:

hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop dfs -FromLocal /tmp/gutenberg gutenberg
hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop dfs -ls
Found 1 items
/user/hadoop/gutenberg <dir>
hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop dfs -ls gutenberg
Found 3 items
/user/hadoop/gutenberg/20417-8.txt <r 1> 674425
/user/hadoop/gutenberg/7ldvc10.txt <r 1> 1423808
/user/hadoop/gutenberg/ulyss12.txt <r 1> 1561677

执行 MapRece job

现在,一切准备就绪,我们将在运行Python MapRece job 在Hadoop集群上。像我上面所说的,我们使用的是
HadoopStreaming 帮助我们传递数据在Map和Rece间并通过STDIN和STDOUT,进行标准化输入输出。

hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop jar contrib/streaming/hadoop-0.19.1-streaming.jar
-mapper /home/hadoop/mapper.py -recer /home/hadoop/recer.py -input gutenberg/*
-output gutenberg-output
在运行中,如果你想更改Hadoop的一些设置,如增加Rece任务的数量,你可以使用“-jobconf”选项:

hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop jar contrib/streaming/hadoop-0.19.1-streaming.jar
-jobconf mapred.rece.tasks=16 -mapper ...

一个重要的备忘是关于Hadoop does not honor mapred.map.tasks
这个任务将会读取HDFS目录下的gutenberg并处理他们,将结果存储在独立的结果文件中,并存储在HDFS目录下的
gutenberg-output目录。
之前执行的结果如下:

hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop jar contrib/streaming/hadoop-0.19.1-streaming.jar
-mapper /home/hadoop/mapper.py -recer /home/hadoop/recer.py -input gutenberg/*
-output gutenberg-output

additionalConfSpec_:null
null=@@@userJobConfProps_.get(stream.shipped.hadoopstreaming
packageJobJar: [/usr/local/hadoop-datastore/hadoop-hadoop/hadoop-unjar54543/]
[] /tmp/streamjob54544.jar tmpDir=null
[...] INFO mapred.FileInputFormat: Total input paths to process : 7
[...] INFO streaming.StreamJob: getLocalDirs(): [/usr/local/hadoop-datastore/hadoop-hadoop/mapred/local]
[...] INFO streaming.StreamJob: Running job: job_200803031615_0021
[...]
[...] INFO streaming.StreamJob: map 0% rece 0%
[...] INFO streaming.StreamJob: map 43% rece 0%
[...] INFO streaming.StreamJob: map 86% rece 0%
[...] INFO streaming.StreamJob: map 100% rece 0%
[...] INFO streaming.StreamJob: map 100% rece 33%
[...] INFO streaming.StreamJob: map 100% rece 70%
[...] INFO streaming.StreamJob: map 100% rece 77%
[...] INFO streaming.StreamJob: map 100% rece 100%
[...] INFO streaming.StreamJob: Job complete: job_200803031615_0021

[...] INFO streaming.StreamJob: Output: gutenberg-output hadoop@ubuntu:/usr/local/hadoop$

正如你所见到的上面的输出结果,Hadoop 同时还提供了一个基本的WEB接口显示统计结果和信息。
当Hadoop集群在执行时,你可以使用浏览器访问 http://localhost:50030/ ,如图:

检查结果是否输出并存储在HDFS目录下的gutenberg-output中:

hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop dfs -ls gutenberg-output
Found 1 items
/user/hadoop/gutenberg-output/part-00000 <r 1> 903193 2007-09-21 13:00
hadoop@ubuntu:/usr/local/hadoop$

可以使用dfs -cat 命令检查文件目录

hadoop@ubuntu:/usr/local/hadoop$ bin/hadoop dfs -cat gutenberg-output/part-00000
"(Lo)cra" 1
"1490 1
"1498," 1
"35" 1
"40," 1
"A 2
"AS-IS". 2
"A_ 1
"Absoluti 1
[...]
hadoop@ubuntu:/usr/local/hadoop$

注意比输出,上面结果的(")符号不是Hadoop插入的。

转载仅供参考,版权属于原作者。祝你愉快,满意请采纳哦

⑦ 求简洁优美的python代码例子、片段、参考资料

楼主贴的那段代码好像是我写的那段吧,我来告诉你如何写出来的吧

首先我不是高手,我也没有人教,我的编程都是自学的,我只是一个业余爱好者.

写出这样的代码很简单,就是要多练,我只是把python的基本语法学会,然后就不停地练习,我没有看过楼上的那些资料,我只是不停地码代码,或许有捷径,但是我没有发现.

我从07年开始写python的脚本,我一开始的代码风格也很差,特别是我先学c++,然后再转python的,当写的代码越来越多,对python的了解就会加深,代码风格也会自动改变的,不需要着急,其实这就是对一门语言的了解程度,你可以看看我回答的问题,我的回答就是我对python的理解,如果你能坚持下来,相信7年后你写的代码会比我写得更好.



楼上的题目有点意思,我也写一下,不知道对否

s='''
TheZenofPython,byTimPeters

Beautifulisbetterthanugly.
Explicitisbetterthanimplicit.
Simpleisbetterthancomplex.
.
Flatisbetterthannested.
Sparseisbetterthandense.
Readabilitycounts.
Specialcasesaren'tspecialenoughtobreaktherules.
.
Errorsshouldneverpasssilently.
Unlessexplicitlysilenced.
Inthefaceofambiguity,refusethetemptationtoguess.
Thereshouldbeone--andpreferablyonlyone--obviouswaytodoit.
'reDutch.
Nowisbetterthannever.
*right*now.
,it'sabadidea.
,itmaybeagoodidea.
--let'sdomoreofthose!
'''

importre,collections
tail_map={"'s":'is',"'re":'are',"n't":'not'}
data=collections.Counter(re.findall('w+',re.sub("('s|'re|n't)",lambdamatchobj:tail_map[matchobj.group()],s.lower())))

max_len=max(data.values())
print('Totalwordcount:%d',sum(data.values()))

forwordinsorted(data):
print('%*s=>%d'%(max_len,word,data[word]))

⑧ 想用python编写一个脚本,登录网页,在网页里做一系列操作,应该怎样实现

python编写一个脚本的具体操作:

1、首先,打开python并创建一个新的PY文件。

⑨ 有没有简单一点的Python小例子小项目

可能很多人学编程有个误区,总想着从最基础的原理开始,看了一大堆书一堆视频还是不会,兴趣也早没了。而自己动手写代码是最好的开始方式,不管TM三七二十一,直接就是干,无论是看书还是看视频,确保身边有台电脑可以直接操作,就好比你拿到驾驶说明书一样,最好你已经坐在车上可以直接试验。 只是如果不够细心或对知识的掌握不够,误解某些重要概念,给以后写代码埋下隐患,这个时候你要去看官方文档,看最佳实践,看理论知识。
GitHub有个项目写了大量的Python小脚本,有近万个的Star,我列了30个Pyhon小例子,或许能帮助你快速上手Python,而且他们都是能在实际中可以用到的,有时还能帮助你节省大量时间,相信照着练完之后,代码水平会大有长进。
1、batch_file_rename.py 批量重命名指定目录下面所有文件的后缀名。
2、create_dir_if_not_there.py 如果不存在的目录。
3、Fast Youtube Downloader 多线程高速下载Youtube视频。
4、Google Image Downloader 根据指定词语从Google搜索图片并下载。
5、dir_test.py 检查目录 testdir 是否存在, 如果不存在则创建一个。
6、env_check.py 检查环境变量
7、fileinfo.py 展示文件的元信息

⑩ 如何使用python编写测试脚本

1)doctest
使用doctest是一种类似于命令行尝试的方式,用法很简单,如下

复制代码代码如下:

def f(n):
"""
>>> f(1)
1
>>> f(2)
2
"""
print(n)

if __name__ == '__main__':
import doctest
doctest.testmod()

应该来说是足够简单了,另外还有一种方式doctest.testfile(filename),就是把命令行的方式放在文件里进行测试。

2)unittest
unittest历史悠久,最早可以追溯到上世纪七八十年代了,C++,Java里也都有类似的实现,Python里的实现很简单。
unittest在python里主要的实现方式是TestCase,TestSuite。用法还是例子起步。

复制代码代码如下:

from widget import Widget
import unittest
# 执行测试的类
class WidgetTestCase(unittest.TestCase):
def setUp(self):
self.widget = Widget()
def tearDown(self):
self.widget.dispose()
self.widget = None
def testSize(self):
self.assertEqual(self.widget.getSize(), (40, 40))
def testResize(self):
self.widget.resize(100, 100)
self.assertEqual(self.widget.getSize(), (100, 100))
# 测试
if __name__ == "__main__":
# 构造测试集
suite = unittest.TestSuite()
suite.addTest(WidgetTestCase("testSize"))
suite.addTest(WidgetTestCase("testResize"))

# 执行测试
runner = unittest.TextTestRunner()
runner.run(suite)

简单的说,1>构造TestCase(测试用例),其中的setup和teardown负责预处理和善后工作。2>构造测试集,添加用例3>执行测试需要说明的是测试方法,在Python中有N多测试函数,主要的有:
TestCase.assert_(expr[, msg])
TestCase.failUnless(expr[, msg])
TestCase.assertTrue(expr[, msg])
TestCase.assertEqual(first, second[, msg])
TestCase.failUnlessEqual(first, second[, msg])
TestCase.assertNotEqual(first, second[, msg])
TestCase.failIfEqual(first, second[, msg])
TestCase.assertAlmostEqual(first, second[, places[, msg]])
TestCase.failUnlessAlmostEqual(first, second[, places[, msg]])
TestCase.assertNotAlmostEqual(first, second[, places[, msg]])
TestCase.failIfAlmostEqual(first, second[, places[, msg]])
TestCase.assertRaises(exception, callable, ...)
TestCase.failUnlessRaises(exception, callable, ...)
TestCase.failIf(expr[, msg])
TestCase.assertFalse(expr[, msg])
TestCase.fail([msg])

阅读全文

与简单的python脚本实例相关的资料

热点内容
数控铣床法兰克子程序编程 浏览:173
linux打包命令targz 浏览:996
抖音app是哪个 浏览:407
苹果app怎么上架 浏览:255
NA服务器地址 浏览:427
我的世界如何初始化服务器 浏览:97
哪个手机app天气预报最准 浏览:752
怎样把视频压缩至25m 浏览:570
vivox27文件夹怎么改变 浏览:727
新手玩狼人杀用什么app 浏览:615
pdf在线查看 浏览:954
安卓tv90如何关闭后台 浏览:683
php读取word乱码 浏览:755
minicom源码 浏览:1001
海尔冷柜压缩机 浏览:416
联通服务器如何调试信号 浏览:136
stata新命令 浏览:941
单调栈算法python 浏览:606
微信解压游戏怎么下载 浏览:962
忍三服务器不同如何登上账号 浏览:822