当前位置: 首页 > 图灵资讯 > 行业资讯> 怎么用python输出和输入文件及信息?

怎么用python输出和输入文件及信息?

来源:图灵python
时间: 2025-01-02 17:14:03

所有代码程序由自己编写后,总归是为了服务用户,因为在了解到信息时,使用编程软件,要去自动化处理这些内容,怎么做呢?一起来看下吧~

利用语句有:input和print语句

关于Input代码演示:

name=input('yourname:')
gender=input('youareaboy?(y/n)')

######输入######
yourname:Jack
youareaboy?

welcome_str='Welcometothematrix{prefix}{name}.'
welcome_dic={
'prefix':'Mr.'ifgender=='y'else'Mrs',
'name':name
}

print('authorizing...')
print(welcome_str.format(**welcome_dic))

##########输出##########
authorizing...
WelcometothematrixMr.Jack.

input函数暂停运行,等待键盘输入,直到按下回车,输入的类型永远是字符串

a=input()
1
b=input()
2

print('a+b={}'.format(a+b))
##########输出##############
a+b=12
print('typeofais{},typeofbis{}'.format(type(a),type(b)))
##########输出##############
typeofais<class'str'>,typeofbis<class'str'>
print('a+b={}'.format(int(a)+int(b)))
##########输出##############
a+b=3

文件输入和输出

生产级别的 Python 代码,大部分 I/O 则来自于文件,这里有个in.text:

Mr.Johnsonhadneverbeenupinanaerophanebeforeandhehadreadalotaboutairaccidents,soonedaywhenafriendofferedtotakehimforarideinhisownsmallphane,Mr.Johnsonwasveryworriedaboutaccepting.Finally,however,hisfriendpersuadedhimthatitwasverysafe,andMr.Johnsonboardedtheplane.

Hisfriendstartedtheengineandbegantotaxiontotherunwayoftheairport.Mr.Johnsonhadheardthatthemostdangerouspartofaflightwerethetake-offandthelanding,sohewasextremelyfrightenedandclosedhiseyes.

Afteraminuteortwoheopenedthemagain,lookedoutofthewindowoftheplane,andsaidtohisfriend。

"Lookatthosepeopledownthere.Theylookassmallasants,don'tthey?"

"Thoseareants,"answeredhisfriend."We'restillontheground."

现在读取文件:

  • 去掉所有标点和换行符,将大写变为小写

  • 合并相同的词,统计每个词出现的频率,将词频从大到小排序

  • 将结果按行输出文件out.txt

importre

#你不用太关心这个函数
defparse(text):
#使用正则表达式去除标点符号和换行符
text=re.sub(r'[^\w]','',text)

#转为小写
text=text.lower()

#生成所有单词的列表
word_list=text.split('')

#去除空白单词
word_list=filter(None,word_list)

#生成单词和词频的字典
word_cnt={}
forwordinword_list:
ifwordnotinword_cnt:
word_cnt[word]=0
word_cnt[word]+=1

#按照词频排序
sorted_word_cnt=sorted(word_cnt.items(),key=lambdakv:kv[1],reverse=True)

returnsorted_word_cnt

withopen('in.txt','r')asfin:
text=fin.read()

word_and_freq=parse(text)

withopen('out.txt','w')asfout:
forword,freqinword_and_freq:
fout.write('{}{}\n'.format(word,freq))

##########输出(省略较长的中间结果)##########

大家也可以根据上面代码教学,套用尝试下哦~如需更多python实用知识,点击进入PyThon学习网教学中心