【问题标题】:What is the most efficient way to loop through a text document and count pairs of text next to each other?遍历文本文档并计算相邻文本对的最有效方法是什么?
【发布时间】:2021-03-18 22:34:58
【问题描述】:
  1. 所以我是编码新手,这是我一分钟前制作的一个小 Python 脚本,我不确定它是否非常有效。

  2. 我不确定我是否正确格式化了这个问题,这是脚本:

# Counts the number of pairs (in this case every time 
# 1,6, and a period are next to each other)

counting = 0

# The variable for the array I put all the characters of 
# text in.

array = []

# The variable which counts the amount of characters in 
# the text document

arraycounter = 0

# For loop that goes through text document and puts it in 
# my array.

for x in open("/tmp/python_001.py/Info.txt", "r").read():
    array.append(x)

# While loop that goes through the array and if statement 
# that checks if 1, 6, and a period are next to each other

while arraycounter + 2 < len(array):
    if array[arraycounter] == '1' and array[arraycounter + 1] == '6' and 
    array[arraycounter + 2] == '.': 
        counting += 1
    arraycounter += 1
        
# Prints the counting variable

print(counting)

【问题讨论】:

  • 通过精心挑选的示例文本和您的预期输出,您的问题可能会更清楚。

标签: python arrays for-loop while-loop


【解决方案1】:

你不需要数组,可以slice the string to compare,也可以使用range to iterate

with open("/tmp/python_001.py/Info.txt", "r") as f:
    contents = f.read()

count = 0
for i in range(len(contents) - 2):
    if contents[i:i + 3] == "16.":
        count += 1

print(count)

【讨论】:

    【解决方案2】:

    通常,我们将文件的行读取为:

    with open("....", "r") as file:
        result = file.readlines()
    

    如果您正在寻找“16”。要出现在一个字符串中,你可以写:

    if '16.' in my_string
       ...
    

    如果您认为 '16.'在一个字符串中出现不止一次(并且在您的原始代码中,您计算​​多次出现),您可以使用find() 告诉您一个字符串在另一个字符串中的第一次出现(或-1),如果它没有出现。它还有一个start= 参数,因此您可以在查找下一个时跳过已经找到的事件。

    【讨论】:

      猜你喜欢
      • 2020-03-03
      • 1970-01-01
      • 2011-01-14
      • 1970-01-01
      • 2017-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-10
      相关资源
      最近更新 更多