从文件中仅提取每行的第一个单词.. [英] Extract only first word of each line from file..

查看:160
本文介绍了从文件中仅提取每行的第一个单词..的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些内容的文件,我想只显示文件中每行的第一个单词。我试过但没有得到。

===========================

file内容

===========================

你好世界

嗨再次

python编程很棒



================ ==========



代码

=============== ============



I have a file which has some contents and I want to display only first word of each line from file. I tried but not getting.
===========================
file content
===========================
hello world
hi again
python programming is great

==========================

code
===========================

f=open("file1.txt","r+")
content=f.read()
for line in content.split(' ',1):
    print(line)

推荐答案

我不做Python所以我只会显示一些伪代码(详见我的评论):



- 拆分原始tex将文件放入一个行(字符串)表中。



- 对于每一行(字符串),提取第一个单词(几个方法,来自子字符串(0 ,. 。)正则表达式的方法(更快,imho)。



希望这会有所帮助。
I don't do Python so I will just show some pseudo-code (see my comment for details):

- Split your original text file into a table of lines (strings).

- For each line (string), extract the first word (several methods, from a substring(0,..) method to a regular expression (faster, imho)).

Hope this helps.


而不是阅读所有内容,使用 readline readlines 逐行阅读:https://docs.python.org/2.4/lib/bltin-file-objects.html [ ^ ]。



对于 split('',1),它取决于你认为的单词。标点符号怎么样?另请参阅: https://docs.python.org/2/library/string.html [< a href =https://docs.python.org/2/library/string.htmltarget =_ blanktitle =New Window> ^ ]。



-SA
Instead of reading all content, read line by line using readline or readlines: https://docs.python.org/2.4/lib/bltin-file-objects.html[^].

As to split(' ', 1), it depends on what you consider a word. How about punctuation characters? See also: https://docs.python.org/2/library/string.html[^].

—SA


这篇关于从文件中仅提取每行的第一个单词..的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆