Python-拆分一行并从单词中提取字符
我从输入文件中读取行,并将其拆分为单词,以便处理每个单词。我想从每个单词的特定索引中获取字符。这就是我正在尝试的,它不能正常工作,任何大于单词[0]的内容都超出索引范围。我不明白为什么它不起作用,因为word应该是字符串,而使用字符串进行索引是没有问题的。感谢您的帮助。谢谢 编辑:抱歉,澄清一下-我想从word中获取具有索引的字符。e、 g单词=某物,单词[3]=“e”。我正在使用fileinput模块Python-拆分一行并从单词中提取字符,python,python-3.x,Python,Python 3.x,我从输入文件中读取行,并将其拆分为单词,以便处理每个单词。我想从每个单词的特定索引中获取字符。这就是我正在尝试的,它不能正常工作,任何大于单词[0]的内容都超出索引范围。我不明白为什么它不起作用,因为word应该是字符串,而使用字符串进行索引是没有问题的。感谢您的帮助。谢谢 编辑:抱歉,澄清一下-我想从word中获取具有索引的字符。e、 g单词=某物,单词[3]=“e”。我正在使用fileinput模块 import fileinput line = f.readline() for w
import fileinput
line = f.readline()
for word in line.split():
print(word, end="")
r = int(word[1]) // I want to get the 2nd character from this word in the line
c = int(word[3])
输入文件:
1 (1,1)
2 (1,2) (1,3)
5 (2,1) (2,2) (3,1) (3,2) (3,3)
4 (2,3) (2,4) (1,4) (1,5)
3 (3,4) (3,5) (2,5)
我想设置r=括号中的第一个数字,c=括号中的第二个数字我不确定我是否理解你的意思,但让我试试。Split接受两个参数:分隔符和最大拆分数。您告诉python只做一个,然后选择结果数组的第二部分。也许可以尝试以下几点:
for word in line.split(''):
print(word, end="")
# you should check the length of the word
r = int(word[1])
c = int(word[3])
希望对你有所帮助,我不确定我是否明白你的意思,但让我试试。Split接受两个参数:分隔符和最大拆分数。您告诉python只做一个,然后选择结果数组的第二部分。也许可以尝试以下几点:
for word in line.split(''):
print(word, end="")
# you should check the length of the word
r = int(word[1])
c = int(word[3])
希望它能有所帮助。听起来您只需要在过滤掉括号和逗号时更加小心。您可以使用这样的功能,它应该非常强大:
line = "(1,1) (1,7)\n"
for tup in line.split():
print(tup)
# drop parentheses and split at the comma
vals = tup[1:-1].split(',')
r = int(vals[0])
c = int(vals[1])
print(r)
print(c)
结果:
(1,1)
1
1
(1,7)
1
7
但实际上,如果所有值都是个位数,那么代码也应该可以正常工作:
line = "(1,1) (1,7)\n"
for word in line.split():
print(word)
r = int(word[1])
c = int(word[3])
print(r)
print(c)
# gives same result
听起来您只需要在过滤掉括号和逗号时更加小心。您可以使用这样的功能,它应该非常强大:
line = "(1,1) (1,7)\n"
for tup in line.split():
print(tup)
# drop parentheses and split at the comma
vals = tup[1:-1].split(',')
r = int(vals[0])
c = int(vals[1])
print(r)
print(c)
结果:
(1,1)
1
1
(1,7)
1
7
但实际上,如果所有值都是个位数,那么代码也应该可以正常工作:
line = "(1,1) (1,7)\n"
for word in line.split():
print(word)
r = int(word[1])
c = int(word[3])
print(r)
print(c)
# gives same result
您也可以尝试以下方法:
from ast import literal_eval
with open('data.txt') as in_file:
for line in in_file:
_, *rest = line.strip().split()
for x, y in map(literal_eval, rest):
print((x, y))
print(x)
print(y)
将从文件中读取的字符串元组转换为整数元组,并将其打印出来:
(1, 1)
1
1
(1, 2)
1
2
(1, 3)
1
3
...
您也可以尝试以下方法:
from ast import literal_eval
with open('data.txt') as in_file:
for line in in_file:
_, *rest = line.strip().split()
for x, y in map(literal_eval, rest):
print((x, y))
print(x)
print(y)
将从文件中读取的字符串元组转换为整数元组,并将其打印出来:
(1, 1)
1
1
(1, 2)
1
2
(1, 3)
1
3
...
数据,其他人需要
行
的定义来帮助数据,其他人需要行
的定义来帮助数据