[英]Get words from first line until first space and without first character in python
I have a textfile where I want to extract the first word, but without the first character and put it into a list. 我有一个文本文件,我要在其中提取第一个单词,但不提取第一个字符并将其放入列表中。 Is there a way in python to do this without using regex?
python中有没有一种方法可以不使用正则表达式呢? A text example of what I have looks like:
我所拥有的文本示例如下所示:
#blabla sjhdiod jszncoied
Where I want the first word in this case blabla without the #. 在这种情况下,我希望第一个单词不带#blabla。 If regex is the only choice, then how will the regex look like?
如果正则表达式是唯一的选择,那么正则表达式将如何?
This should do the trick: 这应该可以解决问题:
l = []
for line in open('file'):
l.append(line.split()[0][1:])
Edit: If you have empty lines, this will throw an error. 编辑:如果您有空行,这将引发错误。 You will have to check for empty lines.
您将必须检查是否有空行。 Here is a possible solution:
这是一个可能的解决方案:
l = []
for line in open('file'):
if line.strip():
l.append(line.split()[0][1:])
Python方式:
my_list = [line.split(' ', 1)[0][1:] for line in open('file') if line.startswith('#')]
a textfile where I want to extract the first word , but without the first character and put it into a list
我想提取第一个单词但不带第一个字符的文本文件 ,并将其放入列表中
result = []
with open('file.txt', 'r') as f:
l = next(f).strip() # getting the 1st line
result.append(l[1:l.find(' ')])
print(result)
The output: 输出:
['blabla']
Simple enough if your input is so regular: 如果您的输入非常常规,则非常简单:
s = "#blabla sjhdiod jszncoied"
s.split()[0].strip('#')
blabla
split
splits on whitespace by default. split
默认情况下在空白处分割。 Take the first token and strip away '#'
. 取得第一个令牌并去除
'#'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.