首页 \ 问答 \ 只有当它以特定单词开头时才打印下一行(print next line only if it begins with a specific word)

只有当它以特定单词开头时才打印下一行(print next line only if it begins with a specific word)

我对python有点新意,我想知道是否有人可以提供帮助。 基本上我正在读取文件的内容,当我找到单词“prb”时,我想使用next()函数检查下一行,如果它以单词“rt”开头,我想打印两行。 到目前为止,我写了这段代码:

    with open('/home/user/Desktop/3rdstep.txt', 'r') as f:
    f.readline()
    for line in f:
            if "prb" in line:
                    try:
                            myword = next(f)
                            if "rt" in myword:
                                    print(line.strip())
                                    print(myword)
                    except:
                            print("pass")

这很好但唯一的问题是它会随机跳过“rt”字,原因我不知道。 任何人都可以帮忙或让别人做类似的事吗?

谢谢


I am a bit new to python and I was wondering if anyone can help. Basically I am reading contents of a file and when I find the word "prb" I want to check the next line using the next() function and if it starts with the word "rt", i want to print both lines. So far I wrote this piece of code:

    with open('/home/user/Desktop/3rdstep.txt', 'r') as f:
    f.readline()
    for line in f:
            if "prb" in line:
                    try:
                            myword = next(f)
                            if "rt" in myword:
                                    print(line.strip())
                                    print(myword)
                    except:
                            print("pass")

This works fine but the only problem is that it skips randomly "rt" words for a reason I don't know. Can anyone help please or have someone done something similar?

Thanks


原文:https://stackoverflow.com/questions/37032554
更新时间:2022-03-16 13:03

最满意答案

std::cout << std::to_string(2) << std::endl;
for (unsigned int i = 3; i<240; i += 2) {
    unsigned int j = 3;
    int sq = sqrt(i);
    for (; j <= sq; j += 2) if (!(i%j)) break;
    if (j>sq) std::cout << std::to_string(i) << std::endl;
}

首先,主要定义:素数(或素数)是大于1的自然数,除了1和自身之外没有正除数。

所以你可以跳过所有的偶数(因此... i + = 2)。 此外,没有必要尝试划分大于sqrt(i)的数字,因为它将具有小于sqrt(i)的除数,并且代码找到并移动到下一个数字。 只考虑奇数,意味着我们可以跳过偶数作为除数(因此... j + = 2)。

在你的代码中,显然有初学者错误,比如(x = 0)而不是x == 0。 而且逻辑也不能说服。 我同意@NathanOliver,你需要学习使用调试器来查找所有错误。 其余的,与研究祝你好运。


std::cout << std::to_string(2) << std::endl;
for (unsigned int i = 3; i<240; i += 2) {
    unsigned int j = 3;
    int sq = sqrt(i);
    for (; j <= sq; j += 2) if (!(i%j)) break;
    if (j>sq) std::cout << std::to_string(i) << std::endl;
}

first of all, the prime definition: A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.

so you can skip all the even numbers (and hence ... i+=2). Moreover no point to try to divide for a number greater than sqrt(i), because then it will have a divisor less than sqrt(i) and the code finds that and move to the next number. Considering only odd numbers, means that we can skip even numbers as divisors (hence ... j+=2).

In your code there are clearly beginner errors, like (x = 0) instead of x==0. but also the logic doesn't convince. I agree with @NathanOliver, you need to learn to use a debugger to find all the errors. For the rest, good luck with the studies.

相关问答

更多
  • 您的示例解决方案根本不符合问题的规范。 您应该首先关注编写static boolean isPrime(int m, int[] P)方法。 所有这些方法需要做的是: 迭代P的内容 如果元素均匀地除以m ,则m为复合 - 返回false 如果元素的平方大于m ,则m为素数 - 返回true 。 这听起来像问题描述这种情况永远不会发生, P只会在穿越sqrt(m)边界之前只有从2到1的素数 如果已经测试了P所有元素,则m是素数 - 返回true 之后你可以编写main来制作primes数组并使用描述的循环构建 ...
  • 没有确切的细节就不可能知道,但两种最可能的可能性是: 在使用之前, sum未初始化为0 您遇到溢出 ,因为数字的总和太大而不适合它。 这显然取决于sum的类型和范围。 编辑: 编辑后的代码适用于我,对于小范围(请注意,对于更大的范围,还应考虑问题#2)。 你可能会误读结果,尝试添加endl到cout << sum ; It is impossible to know without the exact details but two most likely possibilities are: sum wa ...
  • 当然,第一个错误是你的make_pair_table函数中你没有调用get_pairs而是调用get_primes ,但似乎你已经修复了它。 另一个错误是,只要遇到素数对,您只需将对中的第一个数字添加到对列表中。 例如,对于素数3,5,7,11你比较3和5,然后加3,然后你比较5和7并加5,但是你比较7和11并且不加7,即使它是在一对素数中。 解决此问题的一种方法是为每对添加两个素数,但是您必须检查第一个数字是否已经是最后一对的一部分。 for i in range(len(prime_list) - 1) ...
  • 一个简单的Eratosthenes筛子就像拍板一样运行。 这在我的盒子里计算了不到一秒的第1,000,000个素数: class PrimeSieve { public List Primes; private BitArray Sieve; public PrimeSieve(int max) { Primes = new List { 2, 3 }; // Must include at least 2, 3. Si ...
  • 首先,我想发布代码的正确语法。 i = 2 while(i < 50): j = 2 while(j <= (i/j)): if not(i%j): break j = j + 1 if (j > i/j): print(i, " is prime") i = i + 1 通过编写这样的代码,我们可以做几件事。 我们能做的第一件事是获得一个很好 ...
  • 我建议使用像Eclipse这样的IDE,它会显示是否有任何死代码。 在你的情况下,内循环的i ++是死代码,因为你在做i = n + 1。 第一次迭代后,我总是大于n。 使用以下代码作为参考 public static void main(String[] args) { HashSet A = new HashSet<>(); A.add(2); boolean addNumber; for (int n = 3; n < 100; n++) { ...
  • std::cout << std::to_string(2) << std::endl; for (unsigned int i = 3; i<240; i += 2) { unsigned int j = 3; int sq = sqrt(i); for (; j <= sq; j += 2) if (!(i%j)) break; if (j>sq) std::cout << std::to_string(i) << std::endl; } 首先,主要定义:素数(或素数 ...
  • 你可以使用ArrayList而不是像这样的int数组: import java.util.ArrayList; public static void main (String[] args) { int x=10;//end of the interval int y=2;//first of the interval ArrayList nonPrime = new ArrayList(); for(int i=y+1;i< ...
  • 不需要遍历内部循环的整个范围,对于内部循环,可能的值从2开始到<=那个数字/ 2 。 就像你想要检查99是否为素数一样,你需要将内循环从2设置为49(99/2是该数字的最大可能因子),所以不要遍历其余的全部。 因此,如果你将内部循环从2迭代到98,那么它意味着在49之后迭代这个循环,考虑一下。 #include #include using namespace std; int main() { //vector n; // will store ...
  • 没有办法在没有任何循环的情况下对无限范围的数字进行素性测试。 这个问题的递归解决方案也非常有限,因为它们不可扩展。 No there is no way to perform primality test on an unlimited range of numbers without using any loop. Recursive solutions to this problem are also very limited in that they are not scalable.

相关文章

更多

最新问答

更多
  • 如何在Laravel 5.2中使用paginate与关系?(How to use paginate with relationships in Laravel 5.2?)
  • linux的常用命令干什么用的
  • 由于有四个新控制器,Auth刀片是否有任何变化?(Are there any changes in Auth blades due to four new controllers?)
  • 如何交换返回集中的行?(How to swap rows in a return set?)
  • 在ios 7中的UITableView部分周围绘制边界线(draw borderline around UITableView section in ios 7)
  • 使用Boost.Spirit Qi和Lex时的空白队长(Whitespace skipper when using Boost.Spirit Qi and Lex)
  • Java中的不可变类(Immutable class in Java)
  • WordPress发布查询(WordPress post query)
  • 如何在关系数据库中存储与IPv6兼容的地址(How to store IPv6-compatible address in a relational database)
  • 是否可以检查对象值的条件并返回密钥?(Is it possible to check the condition of a value of an object and JUST return the key?)
  • GEP分段错误LLVM C ++ API(GEP segmentation fault LLVM C++ API)
  • 绑定属性设置器未被调用(Bound Property Setter not getting Called)
  • linux ubuntu14.04版没有那个文件或目录
  • 如何使用JSF EL表达式在param中迭代变量(How to iterate over variable in param using JSF EL expression)
  • 是否有可能在WPF中的一个单独的进程中隔离一些控件?(Is it possible to isolate some controls in a separate process in WPF?)
  • 使用Python 2.7的MSI安装的默认安装目录是什么?(What is the default installation directory with an MSI install of Python 2.7?)
  • 寻求多次出现的表达式(Seeking for more than one occurrence of an expression)
  • ckeditor config.protectedSource不适用于editor.insertHtml上的html元素属性(ckeditor config.protectedSource dont work for html element attributes on editor.insertHtml)
  • linux只知道文件名,不知道在哪个目录,怎么找到文件所在目录
  • Actionscript:检查字符串是否包含域或子域(Actionscript: check if string contains domain or subdomain)
  • 将CouchDB与AJAX一起使用是否安全?(Is it safe to use CouchDB with AJAX?)
  • 懒惰地初始化AutoMapper(Lazily initializing AutoMapper)
  • 使用hasclass为多个div与一个按钮问题(using hasclass for multiple divs with one button Problems)
  • Windows Phone 7:检查资源是否存在(Windows Phone 7: Check If Resource Exists)
  • 无法在新线程中从FREContext调用getActivity()?(Can't call getActivity() from FREContext in a new thread?)
  • 在Alpine上升级到postgres96(/ usr / bin / pg_dump:没有这样的文件或目录)(Upgrade to postgres96 on Alpine (/usr/bin/pg_dump: No such file or directory))
  • 如何按部门显示报告(How to display a report by Department wise)
  • Facebook墙贴在需要访问令牌密钥后无法正常工作(Facebook wall post not working after access token key required)
  • Javascript - 如何在不擦除输入的情况下更改标签的innerText(Javascript - how to change innerText of label while not wiping out the input)
  • WooCommerce / WordPress - 不显示具有特定标题的产品(WooCommerce/WordPress - Products with specific titles are not displayed)