简体   繁体   English

如何将for循环与列表项结合

[英]How can I combine for loop with list items

I have some names in a list, I want to combine the names with some sentences that I have in a text file. 我在列表中有一些名称,我想将这些名称与文本文件中包含的某些句子组合在一起。

this is my test.txt, it contains following: 这是我的test.txt,其中包含以下内容:

This is line 1
This is line 2
This is line 3

This is my code to combine the text file and list item 这是我的代码,用于结合文本文件和列表项

name = ['anjana','ashish','dilip','gaurav','grishma','hira','ishika','manoj',
        'muna']
x=1


with open('test.txt', mode = 'r+', encoding="utf=8") as f:

 for y in name:
  for line in f:
      if line.rstrip():
          line_strip = line.strip()
          tag_strip = '<s> ' + line.strip() +' </s>'
          subject = str(name[0])
          tag_end = ' (' + subject +'_'+ str(x).zfill(2) +')'
          print (tag_strip +tag_end)


          x = x+1

with this I can get the desired result for only the first item in the list. 这样,我可以获得列表中仅第一项的所需结果。 it doesn't iterate thru all the items 它不会遍历所有项目

<s> This is line 1 </s> (anjana_01)
<s> This is line 2 </s> (anjana_02)
<s> This is line 3 </s> (anjana_03)

what I am looking for is 我正在寻找的是

<s> This is line 1 </s> (anjana_01)
<s> This is line 2 </s> (anjana_02)
<s> This is line 3 </s> (anjana_03)
.......... so on until
<s> This is line 1 </s> (muna_01)
<s> This is line 2 </s> (muna_02)
<s> This is line 3 </s> (muna_03)

After the file is opened you've iterated through it and for line in f doesn't give you any more elements. 打开文件后,您将对其进行遍历, for line in f中的行不再为您提供任何元素。

Try putting with open('test.txt', mode = 'r+', encoding="utf=8") as f after for y in name 尝试for y in name之后with open('test.txt', mode = 'r+', encoding="utf=8") as f for y in name

Better still, read your lines in once and add the names afterwards, to reduce the IO component of the program. 更好的是,一次读入各行,然后再添加名称,以减少程序的IO组件。

Try the following approach: 请尝试以下方法:

>>> txtdata = """This is line 1
... This is line 2
... This is line 3"""
>>> 
>>> name = ['anjana','ashish','dilip','gaurav','grishma','hira','ishika','manoj','muna']
>>>
>>> result = []
>>> 
>>> for i in name:
...     for idx, data in enumerate(txtdata.splitlines(), 1):
...             result.append('<s> ' + data + ' </s>' + ' (' + i + '_0' + str(idx) + ')')
... 
>>> for i in result:
...     print(i)
... 
<s> This is line 1 </s> (anjana_01)
<s> This is line 2 </s> (anjana_02)
<s> This is line 3 </s> (anjana_03)
...
...
<s> This is line 1 </s> (muna_01)
<s> This is line 2 </s> (muna_02)
<s> This is line 3 </s> (muna_03)
>>> 

When you say for line in f you are consuming the data from the file handle. 当您for line in f说时for line in f您正在使用文件句柄中的数据。 You should instead store the data, and iterate over it multiple times. 相反,您应该存储数据,并对其进行多次遍历。 You can say f.readlines() to get all the lines, then use them in your loop repeatedly. 您可以说f.readlines()获取所有行,然后在循环中重复使用它们。

There are several issues. 有几个问题。 You could go on with using seek() method to move cursor to the beginning of the file after each iteration. 您可以继续使用seek()方法在每次迭代后将光标移动到文件的开头。 Secondly, you use only first element from the name list instead of using variable y . 其次,仅使用name列表中的第一个元素,而不使用变量y This has most necessary improvments: 这是最必要的改进:

name = ['anjana','ashish','dilip','gaurav','grishma','hira','ishika','manoj',
        'muna']
x=1


with open('test.txt', mode = 'r+') as f:

 for y in name:
  for line in f:
      if line.rstrip():
          line_strip = line.strip()
          tag_strip = '<s> ' + line.strip() +' </s>'
          subject = str(y)
          tag_end = ' (' + subject +'_'+ str(x).zfill(2) +')'
          print (tag_strip +tag_end)
  f.seek(0, 0)

Please, pay attention to proper line formatting. 请注意正确的行格式。 No one uses one space per indentation. 每个缩进没有人使用一个空格。 Use 4 instead. 改用4。 And more descriptive names like 还有更多描述性的名称,例如

names = ['anjana', 'ashish', ...]
(...)
for name in names:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在循环结束时将 for 循环和 append 项目运行到列表中? - How can I run a for loop and append items to a list at the end of the loop? 当没有更多项目要附加到列表时,如何打破循环? - How can I break a loop when there are no more items to append to list? 如何从 for 循环 python 的列表中删除项目 - How can i delete items from list in for loop python 如何以循环方式组合两个数组,以便在 python (django) 中出现一个列表的 3 个项目,然后出现另一个列表的 1 个项目 - How do I combine two arrays in for loop fashion so the 3 items of one list appear then 1 item of the other list appears, in python (django) 如何在Python中将条件循环与for循环结合? - How can I combine a conditional with a for loop in Python? 如何将列表中的项目合并为一个 - How to combine items in a list as one 如何将这样的字典合并到 1 个列表中? - How can I combine dictionary like this to 1 list? 如何在 python 中使用 for 循环对两个列表项的乘积求和? - How can I sum the product of two list items using for loop in python? 我可以在没有for循环的情况下搜索对象列表中的项目吗? - Can I search for items in list of objects without a for loop? 为什么我不能使用 for in 循环操作列表项? (Python) - Why can't I manipulate a list items using for in loop? (Python)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM