Python - 分割一行并从单词中提取字符

时间:2018-02-25 05:06:30

标签: python python-3.x

我正在从输入文件中读取行并将其拆分为单词,以便我可以处理每个单词。我想从特定索引的每个单词中获取字符。这就是我正在尝试的,它不能正常工作,任何大于word [0]的东西都不在索引之内。我不明白为什么它不起作用,因为word应该是一个字符串,索引与字符串工作没有问题。任何帮助表示赞赏。感谢

编辑:抱歉,澄清一下 - 我想通过索引从单词中获取字符。例如word = something,word [3] ='e'。我正在使用fileinput模块

 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 = perenthesis中的第一个数字,c =括号中的第二个数字

3 个答案:

答案 0 :(得分:4)

听起来你需要更加小心地过滤出括号和逗号。你可以使用这样的东西,它应该非常强大:

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

答案 1 :(得分:0)

我不确定我是否跟着你,但让我试试。 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])

希望有所帮助

答案 2 :(得分:0)

你也可以尝试这样的事情:

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)

将从文件中读取的字符串元组转换为带有ast.literal_eval的整数元组并将其打印出来:

(1, 1)
1
1
(1, 2)
1
2
(1, 3)
1
3
...
相关问题